gpt4 book ai didi

Java 线程池执行器

转载 作者:太空宇宙 更新时间:2023-11-04 14:44:28 24 4
gpt4 key购买 nike

我在理解 Java ThreadPoolExecutor 时遇到了很大的困难。例如,我想计算数字1-1000的平方:

public static void main(String[] args) throws InterruptedException, ExecutionException {

Callable<ArrayList<Integer>> c = new squareCalculator(1000);
ExecutorService executor = Executors.newFixedThreadPool(5);
Future<ArrayList<Integer>> result = executor.submit(c);


for(Integer i: result.get()){
System.out.println(i);
}

}

还有

public class squareCalculator implements Callable<ArrayList<Integer>>{
private int i;
private int max;

private int threadID;
private static int id;
private ArrayList<Integer> squares;

public squareCalculator(int max){
this.max = max;
this.i = 1;
this.threadID = id;
id++;
squares = new ArrayList<Integer>();

}

public ArrayList<Integer> call() throws Exception {
while(i <= max){
squares.add(i*i);
System.out.println("Proccessed number " +i + " in thread "+this.threadID);
Thread.sleep(1);
i++;
}
return squares;

}
}

现在我的问题是,我只有一个线程进行计算。我预计会得到 5 个线程。

最佳答案

如果您希望Callable同时运行5次,则需要提交它5次。您只提交了一次,然后询问了 5 次结果。

submit() 的 Javadoc:

Submits a value-returning task for execution and returns a Future representing the pending results of the task. The Future's get method will return the task's result upon successful completion.

您会看到 submit() 的 Javadoc 使用单数形式表示“task”,而不是“tasks”。

修复很简单:多次提交:

Future<ArrayList<Integer>> result1 = executor.submit(c);
Future<ArrayList<Integer>> result2 = executor.submit(c);
Future<ArrayList<Integer>> result3 = executor.submit(c);
/// etc..

result1.get();
result2.get();
result3.get();
// etc..

关于Java 线程池执行器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24595921/

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