1

此类在执行 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() 挂在这里?

4

1 回答 1

2

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

于 2012-06-12T18:33:15.533 回答