Java:ExecutorService比手动线程执行效率低吗?

我有一个多线程的应用程序.当使用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();
...

解决方法

这是你的问题:
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().您实际上可以使用它来获取任务的Futures集合,如果任务实际上生成您想要的输出,这将非常有用.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...