簡體   English   中英

Java - 如何在外部ExecutorService上調用shutdown時,使ExecutorService在另一個ExecutorService中運行而不關閉?

[英]Java - How to make an ExecutorService running inside another ExecutorService not to shutdown when shutdown is invoked on the outer 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()blastExecutor.shutdown()調用mailExecutor關閉(?)

這只是一個示例代碼,並且在identifyDealers()方法中發生了很多業務。 如何使sendEmail異步並使blastExecutor.shutdown()不等待mailExecutor關閉?

你的假設似乎是錯誤的, 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.awaitTerminatione2.awaitTermination ,在輸出中它也會顯示e2從未收到關閉信號:

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

如果mailExecutor確實關閉了,我認為還有其他的東西在你的代碼中沒有顯示。 由於您的代碼的基本結構現在看起來,您正在運行單個任務並立即關閉執行程序,這可能意味着您可能甚至不需要blastExecutor

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM