gpt4 book ai didi

java - 多线程 Java 仅使用一个线程

转载 作者:行者123 更新时间:2023-12-01 18:43:58 25 4
gpt4 key购买 nike

我正在开发这个项目,我想在我的代码中使用多线程。所以我开发了这一小段代码并对其进行了测试,但结果发现它只使用了我计算机中的一个线程。有人可以告诉我它有什么问题以及如何改进吗?

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;
}

这是可调用的

class Count implements Callable<Integer> {
//where the processing code is
}

所以当我运行这个程序时,它只使用了我的 CPU 的 12.5%,这只是一个线程......大家有想法吗?

谢谢

最佳答案

问题出在你的循环中:

for (int i = 0; i < coreCount; i++) {
Future<Integer> result = e1.submit(new Count(coreCount, i, charlist));
total += result.get();
}

它的作用是:

  • 提交计算
  • Future 对象调用 get()等待计算完成
  • 然后执行循环的下一次迭代

因此,在每次迭代中,您的代码都会等待计算完成,然后再提交下一次迭代。

您应该创建两个循环,一个用于提交计算,它将所有 Future 对象存储在集合中,然后第二个循环调用 get()每个 Future 对象。

关于java - 多线程 Java 仅使用一个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18682511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com