我的用例:
我相信HttpClient后面的池管理器可以进行类似的设置。我试图使用ThreadPoolExecutor来实现它但无法找到方法。有可能吗?
这是一个测试的例子。
public class ExecutorExample {
public static void main(String[] args) throws InterruptedException {
int minPoolSize = 2;
int maxPoolSize = 10;
int ttlMillis = 100;
ThreadPoolExecutor startupExecutor = new ThreadPoolExecutor(minPoolSize,
maxPoolSize, // surprisingly this is not obeyed.
ttlMillis,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName() + ":" + startupExecutor.getCorePoolSize());
startupExecutor.execute(new MyRunnable(i));
}
for (int i = 0; i < 20; i++) {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + ":" + startupExecutor.getCorePoolSize());
}
}
}
class MyRunnable implements Runnable {
int n;
public MyRunnable(int n) {
this.n = n;
}
@Override
public void run() {
try {
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + ":" + n);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
这个怎么样:
ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
编辑:通常我使用的队列是有界阻塞队列。
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(queueCapacity, true);
EDIT2:最大池大小仅在队列满时启动。由于您使用的是无界队列,因此线程数不会高于2. Se链接如下。
rules-of-a-threadpoolexecutor-pool-size
放大小1,你会看到差异。
new LinkedBlockingQueue<>(1));
编辑3:在您的示例中,使用startupExecutor.getCorePoolSize()
更改startupExecutor.getPoolSize()
。