Java 执行程序服务未并行处理

Java Executor Service Is Not Processing Parallely

我正在尝试使用 ExecutorService 并行 运行 多个服务。但是我无法并行执行。

我写了java.util.concurrent.TimeUnit.MINUTES.sleep(1)在Service1等一分钟class.

但是Service2是在Service1处理完之后才处理的。

以下是我的代码片段,如果我对 ExecutorService 的理解有误,请更正me/code

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

是一个构造函数,主线程在做new Service1()时会调用它。 所以是的,它必须完成才能提交服务。

更新:

在你原来的 post 中,睡眠是在调用方法中,它起作用了。现在,您的 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 实例甚至无法在构造函数完成之前提交。