我有一个方法start()
,它创建一个带有lambda的Runnable。在方法内部,我启动一个使用此Runnable的ScheduledExecutorService。我认为如果只使用一个线程来执行任务,我就不会有问题,但如果我开始使用多个线程并在内部传递相同的Runnable,会发生什么。示例代码如下:
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();
}
}
如果将代码更改为使用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);
}
....
}
提前致谢。
答案 0 :(得分:0)
如果将代码更改为使用2个线程
会发生什么
嗯,两个任务将同时执行固定延迟。他们都会尝试从服务A接收消息,使用服务B做某事并删除他们收到的每条消息,然后在一秒钟之后再次进行。
您的需求以及serviceA和serviceB是否能够处理并发呼叫尚不清楚,因此您可以自行决定。