gpt4 book ai didi

java - Java Executor 的多线程

转载 作者:行者123 更新时间:2023-11-30 06:37:03 25 4
gpt4 key购买 nike

我遇到了以下问题。比如说,我有一个包含 1000 个项目的请求,我想利用 Java Executor 来解决这个问题。

这里是主要方法

public static void main(String[] args) {

//Assume that I have request object that contain arrayList of names
//and VectorList is container for each request result

ExecutorService threadExecutor = Executors.newFixedThreadPool(3);
Vector<Result> vectorList = new Vector<Result();

for (int i=0;i<request.size();i++) {
threadExecutor.execute(new QueryTask(request.get(i).getNames, vectorList)
}

threadExecutor.shutdown();

response.setResult(vectorList)

}

这是 QueryTask 类

public QueryTask() implements Runnable {

private String names;
private Vector<Result> vectorList;

public QueryTask(String names, Vector<Result> vectorList) {
this.names = names;
this.vectorList = vectorList;
}

public void run() {
// do something with names, for example, query database
Result result = process names;

//add result to vectorList
vectorList.add(result);
}


}

因此,基于上面的示例,我想为请求中的每个数据创建线程池,同时运行它,并将结果添加到 VectorList。在流程结束时,我希望所有结果都已在 Vector 列表中。

我一直在响应中得到不一致的结果。例如,如果我传递包含 10 个名称的请求,我只会返回 3 或 4 个,有时响应中什么也没有。我期待如果我通过 10,那么我会得到 10。

有谁知道是什么导致了这个问题?

任何帮助将不胜感激。

谢谢

最佳答案

简单的解决方案是添加对 ExecutorService.awaitTermination() 的调用

public static void main(String[] args) {

//Assume that I have request object that contain arrayList of names
//and VectorList is container for each request result

ExecutorService threadExecutor = Executors.newFixedThreadPool(3);
Vector<Result> vectorList = new Vector<Result();

for (int i=0;i<request.size();i++) {
threadExecutor.execute(new QueryTask(request.get(i).getNames, vectorList)
}

threadExecutor.shutdown();
threadExecutor.awaitTermination(aReallyLongTime,TimeUnit.SECONDS);

response.setResult(vectorList)

}

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

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