簡體   English   中英

Java執行器服務未並行處理

[英]Java Executor Service Is Not Processing Parallely

我正在嘗試使用ExecutorService並行運行多個服務。 但是我無法執行並行處理。

我已經編寫了java.util.concurrent.TimeUnit.MINUTES.sleep(1)在Service1類中等待一分鍾。

但是Service2僅在Service1處理之后才處理。

以下是我的代碼段,如果我對ExecutorService的理解錯誤,請更正我/代碼

public void startService() {

    try {
        ExecutorService service = Executors.newFixedThreadPool(3);
        service.submit(new Service1());
        service.submit(new Service2());
        service.submit(new Service3());

        service.shutdown();
        service.awaitTermination(1, TimeUnit.MINUTES);

        System.exit(0);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public class Service1 implements Callable<Object> {

    {
        try {
            java.util.concurrent.TimeUnit.MINUTES.sleep(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object call() throws Exception {
        return null;
    }
}

public class Service2 implements Callable<Object> {

    @Override
    public Object call() throws Exception {
        System.out.println(" Service 2 "); // It prints after 1 minute only.
        return null;
    }
}

public class Service3 implements Callable<Object> {

    @Override
    public Object call() throws Exception {
        System.out.println(" Service 3 "); 
        return null;
    }
}

編碼:

{
    try {
        java.util.concurrent.TimeUnit.MINUTES.sleep(1);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

是一個構造函數,在執行新的Service1()時由主線程調用。 是的,它必須完成才能有機會提交服務。

更新:

在您的原始帖子中,sleep是在call方法中進行的,並且可以正常工作。 現在,您的Service1等效於:

public class Service1 implements Callable<Object> {

    public Service1() {
        try {
            java.util.concurrent.TimeUnit.MINUTES.sleep(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object call() throws Exception {
        return null;
    }
}

並且只有調用方法由執行程序運行。 在構造函數完成之前,甚至無法提交Service1實例。

暫無
暫無

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

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