问题描述
我正在开发一个多线程项目,我需要生成多个线程来测量客户端代码的端到端性能,因为我正在进行负载和性能测试。所以我创建了下面的代码,它使用 ExecutorService
。
I am working on a multithreaded project in which I need to spawn multiple threads to measure the end to end performance of my client code, as I'm doing Load and Performance testing. So I created the below code which is using 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
。所以我很困惑应该使用哪一个。
Now I was reading some article on the Internet. I found out there is ThreadPoolExecutor
as well. So I got confused which one I should be using.
如果我从以下代码中替换上述代码:
If I replace my above code from:
ExecutorService executor = Executors.newFixedThreadPool(20);
for (int i = 0; i < 100; i++) {
executor.submit(new NewTask());
}
to:
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)是正确的使用方式。
will this make any difference? I am trying to understand what is the difference between my original code using ExecutorService
and the new code pasted using ThreadPoolExecutor
. Some of my team mates said second one (ThreadPoolExecutor) is the right way to use.
有人可以为我澄清这个吗?
Can anyone clarify this for me?
推荐答案
以下是 Executors.newFixedThreadPool
的来源:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
它内部使用 ThreadPoolExecutor
如上所示,具有默认配置的类。现在有些情况下默认配置不合适而不是 LinkedBlockingQueue
需要使用优先级队列等。在这种情况下,调用者可以直接处理底层 ThreadPoolExecutor
通过实例化并将所需的配置传递给它。
It internally uses ThreadPoolExecutor
class with default configuration as you can see above. Now there are scenarios where default configuration is not suitable say instead of LinkedBlockingQueue
a priority queue needs to be used etc. In such cases caller can directly work on underlying ThreadPoolExecutor
by instantiating it and passing desired configuration to it.
这篇关于使用LinkedBlockingQueue的ExecutorService与ThreadPoolExecutor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!