简体   繁体   English

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

[英]Is there a way to make an ExecutorService work recursively?

I made the following mistake: 我犯了以下错误:

  1. Called Executors.newFixedThreadThreadPool to make a pool 调用Executors.newFixedThreadThreadPool来创建一个池
  2. Set up a list of Callable objects, such that the call method in turn tried to start a task on the very same thread pool 设置Callable对象列表,以便call方法依次尝试在同一个线程池上启动任务
  3. dump them into the queue with invokeAll 使用invokeAll将它们转储到队列invokeAll

The results were a deadlock on the queue of the executor service. 结果是执行程序服务队列的死锁。

The Javadoc I've read doesn't appear to prohibit this set of activities. 我读过的Javadoc似乎并没有禁止这套活动。 Did I miss something? 我错过了什么? Is there some way to customize the queue or the service so that this could work? 有没有办法自定义队列或服务,以便这可以工作?

My understanding of your question is something like the following test-case, which works as documented (as you say) and I've happily used in production. 我对你的问题的理解类似于下面的测试用例,它按照文档记录(正如你所说的那样)并且我很乐意在生产中使用。 How does your example differ from this? 你的例子与此有何不同?

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);
    }
}

Prints something like: 打印类似于:

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM