【发布时间】:2013-09-08 10:05:57
【问题描述】:
我正在做这个项目,我想在我的代码中使用多线程。所以我开发了这段小代码并对其进行了测试,但结果发现它只使用了我计算机中的一个线程。谁能告诉我它有什么问题以及如何改进它?
public static int choiceCount(List<Character> charlist) throws InterruptedException, ExecutionException {
int coreCount = 8;
ExecutorService e1 = Executors.newFixedThreadPool(coreCount);
Integer total = 0;
for (int i = 0; i < coreCount; i++) {
Future<Integer> result = e1.submit(new Count(coreCount, i, charlist));
total += result.get();
}
e1.shutdown();
return total;
}
这是 Callable
class Count implements Callable<Integer> {
//where the processing code is
}
所以当我运行这个程序时,它只使用了我的 CPU 的 12.5%,而这只是一个线程......各位有什么想法吗?
谢谢
【问题讨论】:
-
在 ExecutorService.submit(callable) 之后立即调用 Future.get() 没有任何意义。它就像 callable.call() 的同步调用一样工作,但是在不同的线程上,这意味着一些不必要的开销。让所有提交在一个循环中,所有在另一个循环中。
标签: java multithreading executorservice callable