Java:ExecutorService比手动线程执行效率低吗?
发布时间:2020-05-24 19:01:56 所属栏目: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无所事事.请改用 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的集合,请注意使用辅助方法 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
