执行完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列表。您可能应该对这些做些有意义的事情。