gpt4 book ai didi

java - Future.get() 不返回

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

我有以下代码:

public class Test {
List<Future> future = new ArrayList<Future>();

public static void main(String args[]) throws Exception {

Adapter b1 = new Adapter();
final ExecutorService threadPool = Executors.newCachedThreadPool();

for(//iterate for number of files) {
while(data exists in file) {
//Call a function to process and update values in db
future.add(threadPool.submit(new Xyz(b1)));
//read next set of data in file;
}
}

try {
for(Future f: future) {
f.get();
}
}
catch(Exception e) {
throw e;
}
}
}

class Xyz implements Runnable {
private Adapter a1;

public Xyz(Adapter al) {
this.a1=a1;
}

@Override
public void run() {
try {
a1.abc();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

当文件数为1时(for循环运行1次),代码运行良好。

但是,当文件数量增加时,代码永远不会从 future.get() 方法返回。

最佳答案

just out of curiosity.. do i need to shutdown the executor somewhere ??

是的,这可能就是问题所在。每个 Future.get() 都会阻塞,直到相应的任务完成,然后一旦所有任务完成,您的 main 线程就会退出。但是您的 java 进程将不会退出,因为线程池线程在后台仍然处于 Activity 状态。完成后,您应该关闭执行器,很可能是 main 方法中的最后一件事。

我还注意到,您提交的许多任务都包装了相同 Adapter 实例,并且全部调用其 abc() 方法 - 检查当在多个线程中同时调用时,其中没有任何内容会发生死锁。

关于java - Future.get() 不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13971801/

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