加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 23:40:07 所属栏目:Java 来源:网络整理
导读:我有一个多线程的应用程序.当使用Thread.start()手动启动线程时,每个并发线程使用恰好25%的CPU(或者恰好一个核心 – 这是在四核机器上).因此,如果我运行两个线程,CPU使用率恰好是50%. 然而,当使用ExecutorService运行线程时,似乎有一个“鬼”线程消耗CPU资
我有一个多线程的应用程序.当使用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集合,如果任务实际上生成您想要的输出,这将非常有用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读