【发布时间】:2019-03-15 19:23:00
【问题描述】:
我正在使用ExecutorService 创建Thread。在run 方法中,它处理一个耗时的操作。完成它需要将近 10 秒。为了测试,这里我使用Thread.sleep(10000);
我的问题是,如果我使用newFixedThreadPool 作为 2000,它真的会一次执行 2000 个线程吗?
public class ThreadPoolTest {
public static void main(String[] args) {
System.out.println(new Date());
ExecutorService executor = Executors.newFixedThreadPool(2000);
IntStream.range(0, 2000).forEach(
i -> {
Runnable worker = new WorkerThread("WorkerThread-" + i);
executor.submit(worker);//calling execute method of ExecutorService
}
);
executor.shutdown();
while (!executor.isTerminated()) { }
System.out.println("Finished all threads");
System.out.println("Main thread finished");
System.out.println(new Date());
}
}
public class WorkerThread implements Runnable{
private String name;
public WorkerThread(String s){
this.name=s;
}
public void run() {
System.out.println(Thread.currentThread().getName()+" (Start) message = "+name);
processData();
}
private void processData(){
try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
我正在这段代码中打印时间。它表明,完成整个过程只需要10秒。这意味着所有 2000 个线程并行执行?听说实际运行的线程数会根据系统中cores的数量而定。但是所有 2000 个线程是如何并行运行的呢?
【问题讨论】:
标签: java multithreading executorservice threadpoolexecutor java-threads