繁体   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