我有一个多线程的应用程序。当使用Thread.start()手动启动线程时,每个并发线程恰好占用25%的CPU (或者说恰好一个内核--这是在四核机器上)。因此,如果我运行两个线程,CPU使用率恰好是50%。
然而,当使用ExecutorService运行线程时,似乎有一个“幽灵”线程在消耗CPU资源!单线程使用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();
...发布于 2011-03-08 10:58:53
这就是你的问题:
while (!executor.isTerminated()) {
}你的"main“方法就是什么也不做就让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集合,如果任务实际上正在生成您想要作为输出的内容,这将非常有用。
https://stackoverflow.com/questions/5227655
复制相似问题