微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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集合,如果任务实际上生成您想要的输出,这将非常有用.

原文地址:https://www.jb51.cc/java/127431.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐