Java - 如何在外部ExecutorService上调用shutdown时,使ExecutorService在另一个ExecutorService中运行而不关闭?

时间:2014-05-15 16:43:37

标签: java executorservice

我在另一个执行者服务中运行Executor服务来发送电子邮件。如果我在外部执行程序上调用shutdown,它正在等待内部执行程序服务关闭,这会大大影响响应时间。

private final ExecutorService blastExecutor = Executors.newFixedThreadPool(20);
private final ExecutorService mailExecutor  = Executors.newFixedThreadPool(2);

public void findDealers() {

          blastExecutor.execute(new Runnable() {
                        public void run() {
                            try {
                                identifyDealers();
                            } catch (Exception e) {

                            }
                        }
                    });

        blastExecutor.shutdown();
        try {
            blastExecutor.awaitTermination(30, TimeUnit.MINUTES);

        } catch (InterruptedException e) {

        }
        logger.info("Completed sending request blasts.");
}

public void identifyDealers() {

           mailExecutor.execute(new Runnable() {
                        public void run() {
                            try {
                                sendEmail();
                            } catch (Exception e) {

                            }
                        }
                    });
}

此处,在blastExecutor.shutdown(),它也会调用mailExecutor的关闭(?)

这只是一个示例代码,identifyDealers()方法中有很多业务发生。如何使sendEmail异步并使blastExecutor.shutdown()不等待mailExecutor的关闭?

1 个答案:

答案 0 :(得分:3)

你的假设似乎是错误的,shutdown()应该只对外部执行者起作用。它不会关闭任何其他执行程序。

以下是基于您的代码的小例子:

ExecutorService e1 = Executors.newFixedThreadPool(20);
final ExecutorService e2 = Executors.newFixedThreadPool(2);

e1.execute(new Runnable() {
    public void run() {
        System.out.println("e1 started");

        e2.execute(new Runnable() {
            public void run() {
                System.out.println("e2 started");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                }
                System.out.println("e2 completed");
            }
        });

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }

    }
});

e1.shutdown();
System.out.println("e1 shut down signal send");

e1.awaitTermination(30, TimeUnit.MINUTES);
System.out.println("e1 terminated");

e2.awaitTermination(30, TimeUnit.MINUTES);
System.out.println("e2 terminated");

应用程序不会终止,它会在e2.awaitTermination上阻止,在输出中它还会显示e2从未收到关闭信号:

e1 started
e1 shut down signal send
e2 started
e1 terminated
e2 completed

如果mailExecutor确实关闭,我认为还有其他内容未在您的代码中显示。由于代码的基本结构现在看来,您正在运行单个任务并立即关闭执行程序,这可能意味着您甚至可能不需要blastExecutor