[英]Java Executor Service Is Not Processing Parallely
I am attempting to run multiple services parallely using ExecutorService. 我正在尝试使用ExecutorService并行运行多个服务。 But i failed to execute parallely.
但是我无法执行并行处理。
I have written java.util.concurrent.TimeUnit.MINUTES.sleep(1) to wait one minute in Service1 class. 我已经编写了java.util.concurrent.TimeUnit.MINUTES.sleep(1)在Service1类中等待一分钟。
But Service2 is processing only after Service1 processed. 但是Service2仅在Service1处理之后才处理。
Below is my code snippet, Kindly correct me/code if my understand about ExecutorService is wrong 以下是我的代码段,如果我对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;
}
}
The code: 编码:
{
try {
java.util.concurrent.TimeUnit.MINUTES.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
}
is a constructor, and it is called by the main thread when it's doing new Service1(). 是一个构造函数,在执行新的Service1()时由主线程调用。 So yeah, it must complete before it has a chance to submit the services.
是的,它必须完成才能有机会提交服务。
UPDATE: 更新:
In your original post, the sleep was in the call method, and it worked. 在您的原始帖子中,sleep是在call方法中进行的,并且可以正常工作。 Now, your Service1 is equivalent to:
现在,您的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;
}
}
And only the call method is run by the executor. 并且只有调用方法由执行程序运行。 the Service1 instance cannot even be submitted before the constructor completes.
在构造函数完成之前,甚至无法提交Service1实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.