有没有办法使递归的ExecutorService工作?

时间:2012-02-20 01:05:35

标签: java

我犯了以下错误:

  1. 调用Executors.newFixedThreadThreadPool制作游泳池
  2. 设置Callable个对象的列表,以便call方法依次尝试在相同的线程池上启动任务
  3. 使用invokeAll
  4. 将它们转储到队列中

    结果是执行程序服务队列的死锁。

    我读过的Javadoc似乎并没有禁止这套活动。我错过了什么?有没有办法自定义队列或服务,以便这可以工作?

1 个答案:

答案 0 :(得分:3)

我对您的问题的理解类似于以下测试用例,其工作原理(如您所说)并且我很乐意在生产中使用。你的例子与此有何不同?

import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Scratch {
    public static void main(String[] args) throws InterruptedException {
        final ExecutorService pool = Executors.newFixedThreadPool(1);
        pool.submit(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                pool.submit(new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        System.out.println(new Date() + ": Second callable being run.");
                        pool.shutdown();
                        return null;
                    }
                });

                System.out.println(new Date() + ": First callable going to sleep...");
                Thread.sleep(2000);
                System.out.println(new Date() + ": First callable finished!");
                return null;
            }
        });

        pool.awaitTermination(2, TimeUnit.MINUTES);
    }
}

打印类似:

Mon Feb 20 01:18:00 GMT 2012: First callable going to sleep...
Mon Feb 20 01:18:02 GMT 2012: First callable finished!
Mon Feb 20 01:18:02 GMT 2012: Second callable being run.