[英]Execute Runnable lambda with more than on threads using ScheduledExecutorService
I have a method start()
that creates a Runnable with a lambda. 我有一个方法
start()
创建一个带lambda的Runnable。 Inside the method I start a ScheduledExecutorService that consumes this Runnable. 在方法内部,我启动一个使用此Runnable的ScheduledExecutorService。 I think if only 1 thread is used to perform the task, I will not have issues, but what is going to happen if I start more than thread and pass the same Runnable inside.
我认为如果只使用一个线程来执行任务,我就不会有问题,但如果我开始使用多个线程并在内部传递相同的Runnable,会发生什么。 Example code is following:
示例代码如下:
public class MessageProcessor {
private final ServiceA serviceA;
private final ServiceB serviceB;
private final ScheduledExecutorService executor;
public MessageProcessor() {
this.executor = Executors.newScheduledThreadPool(1);
this.serviceA = new ServiceA();
this.serviceB = new ServiceB();
}
public void start() {
Runnable messageProcessingTask = () -> {
try {
List<Message> messages = serviceA.receiveMessages();
messages.forEach(m -> {
boolean success = serviceB.doSomething(m);
if (success) serviceB.deleteMessage(m);
else LOG.error("failed to process the message bla bla...");
});
}
catch (Exception e) {
e.printStackTrace();
}
};
executor.scheduleWithFixedDelay(messageProcessingTask, 0, 1, TimeUnit.SECONDS);
}
public void stop() {
executor.shutdown();
}
}
What is going to happen if change the code to use 2 threads : 如果将代码更改为使用2个线程,将会发生什么:
public class MessageProcessor {
.....
public MessageProcessor() {
this.executor = Executors.newScheduledThreadPool(2);
this.serviceA = new ServiceA();
this.serviceB = new ServiceB();
}
public void start() {
Runnable messageProcessingTask = () -> {
try {
List<Message> messages = serviceA.receiveMessages();
messages.forEach(m -> {
boolean success = serviceB.doSomething(m);
if (success) serviceB.deleteMessage(m);
else LOG.error("failed to process the message bla bla...");
});
}
catch (Exception e) {
e.printStackTrace();
}
};
executor.scheduleWithFixedDelay(messageProcessingTask, 0, 1, TimeUnit.SECONDS);
executor.scheduleWithFixedDelay(messageProcessingTask, 0, 1, TimeUnit.SECONDS);
}
....
}
Thanks in advance. 提前致谢。
What is going to happen if change the code to use 2 threads
如果将代码更改为使用2个线程,将会发生什么
Well, both tasks will execute with fixed delay, concurrently. 好吧,两个任务将同时执行固定延迟。 They will both try to receive messages from service A, use service B to do something and delete each message they receive, and then do it again one second later.
他们都会尝试从服务A接收消息,使用服务B做某事并删除他们收到的每条消息,然后在一秒钟之后再次执行。
Whether its what you want and whether serviceA and serviceB are able to process concurrent calls is unknown, so it's up to you to decide. 无论您想要的是什么以及serviceA和serviceB是否能够处理并发呼叫都是未知的,因此您可以自行决定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.