我正在开发一个多线程项目,需要生成多个线程来测试我的客户端代码的端到端性能,因为我正在进行负载和性能测试。所以我编写了下面的代码,它使用ExecutorService
。
以下是使用ExecutorService
的代码:
public class MultithreadingExample {
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(20);
for (int i = 0; i < 100; i++) {
executor.submit(new NewTask());
}
executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}
}
class NewTask implements Runnable {
@Override
public void run() {
//Measure the end to end latency of my client code
}
}
问题陈述:
我在浏览互联网上的一些文章时,发现还有ThreadPoolExecutor
这个东西。所以我很困惑应该使用哪个。
如果我要将我的代码从下面这种形式进行替换:
ExecutorService executor = Executors.newFixedThreadPool(20);
for (int i = 0; i < 100; i++) {
executor.submit(new NewTask());
}
至:
BlockingQueue<Runnable> threadPool = new LinkedBlockingQueue<Runnable>();
ThreadPoolExecutor tpExecutor = new ThreadPoolExecutor(20, 2000, 0L, TimeUnit.MILLISECONDS, threadPool);
tpExecutor.prestartAllCoreThreads();
for (int i = 0; i < 100; i++) {
tpExecutor.execute(new NewTask());
}
这会有什么不同吗?我正在尝试理解使用ExecutorService
的原始代码和新粘贴的使用ThreadPoolExecutor
的代码之间的区别。我的一些团队成员说第二个(ThreadPoolExecutor)是正确的使用方式。
有人能为我澄清一下吗?