【问题标题】:How to update ThreadPoolExecutor threadpool size at runtime如何在运行时更新 ThreadPoolExecutor 线程池大小
【发布时间】:2018-01-15 08:53:44
【问题描述】:

我有以下代码,其中有 3 个类

  1. ThreadPoolTest.java

  2. Parent.java(Runnable)

  3. Child.java(Runnable)

我从 ThreadPoolTest.java 每 10 秒安排一次父线程,一旦父线程启动,它会在其 run() 中创建 100 个子线程。

我的要求是每次启动父线程时,我都想使用同一个线程执行器。

目前我给出的池大小为 50。 在运行时,我想为每个父线程执行更新这个池大小。

这可以实现吗?(有建议吗?)

如果是,我们怎样才能做到这一点?

public class ThreadPoolTest {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Parent parent = new Parent();
        Thread parentThread = new Thread(parent);
        parentThread.setName("Parent");
        try {
            ScheduledExecutorService executor_instant = Executors.newSingleThreadScheduledExecutor();
            executor_instant.scheduleAtFixedRate(parentThread, 0, 10, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


public class Parent implements Runnable {

private static ThreadPoolExecutor executor;
private static int threadPoolSize = 50;
static {
    executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(threadPoolSize);

}
@Override
public void run() {
    for (int i = 0; i < 100; i++) {
        Child child = new Child();
        executor.execute(child);
    }
}
}


public class Child implements Runnable {

@Override
public void run() {
    // TODO Auto-generated method stub

    for (int i = 0; i < 3; i++) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

}

【问题讨论】:

  • 您好,这不是您需要的吗? setMaximumPoolSize(int)
  • 我在 run 方法中创建了执行器,在 for 循环之后我使用了 executor.shutdown(),所以现在我可以为每个创建传递池大小,这正是我所需要的。

标签: java multithreading threadpool


【解决方案1】:

使用setCorePoolSize(int) 设置新的最小尺寸。

我建议您使用Executors.newCachedThreadPool,这样,您将创建线程池大小的责任交给ThreadPoolExecutorThreadPoolExecutor 在需要时创建新线程来执行新任务,并使用@ 重用现有线程987654325@

【讨论】:

  • 我在 run 方法中创建了执行器,在 for 循环之后我使用了 executor.shutdown(),所以现在我可以为每个创建传递池大小,这是我需要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-21
  • 2016-04-10
  • 2011-02-19
  • 1970-01-01
  • 2014-07-09
  • 2013-10-22
  • 1970-01-01
相关资源
最近更新 更多