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

时间:2012-06-12 18:22:11

标签: java executorservice

在执行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);
    }
}

}

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

1 个答案:

答案 0 :(得分:2)

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