48 java multithreading executorservice blockingqueue threadpoolexecutor
我正在开发一个多线程项目,我需要生成多个线程来测量我的客户端代码的端到端性能,因为我正在进行负载和性能测试.所以我创建了以下使用的代码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
}
}
Run Code Online (Sandbox Code Playgroud)
问题陈述:
现在我正在阅读互联网上的一些文章.我发现也有ThreadPoolExecutor
.所以我很困惑我应该使用哪一个.
如果我将以上代码替换为:
ExecutorService executor = Executors.newFixedThreadPool(20);
for (int i = 0; i < 100; i++) {
executor.submit(new NewTask());
}
Run Code Online (Sandbox Code Playgroud)
至:
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());
}
Run Code Online (Sandbox Code Playgroud)
这会有什么不同吗?我试图了解我的原始代码使用ExecutorService
和使用的新代码之间的区别ThreadPoolExecutor
.我的一些队友说第二个(ThreadPoolExecutor)是正确的使用方式.
谁能为我澄清一下这个?
har*_*rsh 73
以下是来源Executors.newFixedThreadPool
:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
Run Code Online (Sandbox Code Playgroud)
ThreadPoolExecutor
如上所示,它在内部使用具有默认配置的类.现在有些情况下默认配置不合适,而不是LinkedBlockingQueue
需要使用优先级队列等.在这种情况下,调用者可以ThreadPoolExecutor
通过实例化并将所需的配置传递给底层来直接处理底层 .
Pet*_*rey 23
那会有什么不同吗?
这将使您的代码更复杂,几乎没有什么好处.
我试图理解我使用ExecutorService的原始代码与我使用ThreadPoolExectuor粘贴的新代码之间的区别是什么?
几乎没有. Executors
创建一个ThreadPoolExecutor来完成真正的工作.
我的一些队友说第二个(ThreadPoolExecutor)是正确的使用方式?
仅仅因为它更复杂并不意味着它是正确的做法.设计人员提供了Executors.newXxxx方法,使您的生活更简单,因为他们希望您使用这些方法.我建议你也使用它们.
NIN*_*OOP 13
执行者#newFixedThreadPool(int nThreads)
ExecutorService executor = Executors.newFixedThreadPool(20);
Run Code Online (Sandbox Code Playgroud)基本上是
return new ThreadPoolExecutor(20, 20,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
Run Code Online (Sandbox Code Playgroud)
2.
BlockingQueue<Runnable> threadPool = new LinkedBlockingQueue<Runnable>();
ThreadPoolExecutor tpExecutor = new ThreadPoolExecutor(20, 2000, 0L,
TimeUnit.MILLISECONDS, threadPool);
Run Code Online (Sandbox Code Playgroud)
在第二种情况下,您只是将maxPoolSize增加到2000,我怀疑您需要它.