gpt4 book ai didi

java - 为什么 Future.get() 方法在调用 shutdownNow() 方法后不返回任何内容?

转载 作者:行者123 更新时间:2023-11-30 04:45:47 28 4
gpt4 key购买 nike

执行调用的 ExecutorService.shutdownNow() 后,该类卡在 Future.get() 方法处。我不知道我犯了什么错误。

该类创建固定线程池,并在 5 秒后超时。如果连续发生 5 个错误,则会调用 shutdownNow()。

 public class TestExecutor {

private AtomicInteger mThresholdCount = new AtomicInteger();
// Default error threshold limit
private int mThresholdLimit = 5;

private ExecutorService executor;

private ThreadPool pool;

public TestExecutor() {
option2();
}

private void option2() {
executor = Executors.newFixedThreadPool(2);
Collection<Future<String>> runnableList = new ArrayList<Future<String>>();
for (int count = 0; count <= 10; count++) {
MyCallable runnable = new MyCallable(count);
runnableList.add(executor.submit(runnable));
}
for (Future<String> future : runnableList) {
try {
System.out.println("Before Get");
future.get();
System.out.println("After Get");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
executor.shutdown();
}

public static void main(String[] args) {
new TestExecutor();
}

private class TimeOutTask extends TimerTask {
private Thread t;

public TimeOutTask(Thread t) {
this.t = t;
}

public void run() {
if (t != null && t.isAlive()) {
t.interrupt();
}
}
}

private class MyCallable implements Callable<String> {

private int count = 0;
private Timer timer = new Timer(true);

public MyCallable(int count) {
this.count = count;
}

@Override
public String call() {
try {
System.out.println("Started Processing " + count);
timer.schedule(new TimeOutTask(Thread.currentThread()), 5000);
Thread.sleep(100000);
System.out.println("Completed processing " + count);
} catch (Exception e) {
System.out.println("Error while processing:" + count);
if (mThresholdCount.incrementAndGet() == mThresholdLimit) {
System.out.println("while processing:" + count
+ " Reached maximum error threshold limit! "
+ "Requested to stop the process.");
if (executor != null) {
executor.shutdownNow();
System.out.println("Shut down now");
}

}
}
return String.valueOf(count);
}
}

}

请帮我理解为什么在 5 个线程连续中断并调用 shutdownNow() 后 get() 卡在这里?

最佳答案

因为列表末尾的 Callables 从未真正被执行,因此永远不会完成(您有 2 个线程和 10 个任务)。您会注意到 shutdownNow() 方法返回一个从未执行的 Runnable 列表。您可能应该用这些做一些有意义的事情。

关于java - 为什么 Future.get() 方法在调用 shutdownNow() 方法后不返回任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11002516/

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