【发布时间】:2018-01-15 08:53:44
【问题描述】:
我有以下代码,其中有 3 个类
ThreadPoolTest.java
Parent.java(Runnable)
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