我有一个多线程应用程序。当使用Thread.start()手动启动线程时,每个并发线程使用恰好25%的CPU(或者恰好一个核心 - 这是在四核机器上)。因此,如果我运行两个线程,CPU使用率恰好是50%。
当使用ExecutorService运行线程时,似乎有一个“鬼”线程消耗CPU资源! One Thread使用50%而不是25%,两个线程使用75%等等。
这可能是某种Windows任务管理器的假象吗?
Excutor服务代码是
ExecutorService executor = Executors.newFixedThreadPool(threadAmount);
for (int i = 1; i < 50; i++) {
Runnable worker = new ActualThread(i);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
和Thread.start()代码是:
ActualThread one= new ActualThread(2,3);
ActualThread two= new ActualThread(3,4);
...
Thread threadOne = new Thread(one);
Thread threadTtwo = new Thread(two);
...
threadOne.start();
threadTwo.start();
...
答案 0 :(得分:16)
这是你的问题:
while (!executor.isTerminated()) {
}
你的“主要”方法是让CPU无所事事。改为使用invokeAll()
,您的线程将在没有繁忙等待的情况下阻止。
final ExecutorService executor = Executors.newFixedThreadPool(threadAmount);
final List<Callable<Object>> tasks = new ArrayList<Callable<Object>>();
for (int i = 1; i < 50; i++) {
tasks.add(Executors.callable(new ActualThread(i)));
}
executor.invokeAll(tasks);
executor.shutdown(); // not really necessary if the executor goes out of scope.
System.out.println("Finished all threads");
由于invokeAll()
需要Callable
的集合,请注意使用辅助方法Executors.callable()
。您实际上可以使用它来获取任务的Future
集合,如果任务实际上产生了您想要的输出,那么这很有用。