简体   繁体   English

使用ScheduledExecutorService在线程上执行Runnable lambda

[英]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);
        }

        ....
    }
  1. Is this approach a bad practice? 这种做法是不好的做法?
  2. If this code lead to errors, how can I produce them? 如果此代码导致错误,我该如何生成它们?
  3. If this is a bad approach, what the best practice would be? 如果这是一个糟糕的方法,最佳做法是什么?

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.

相关问题 使用ScheduledExecutorService在同一期间运行多个线程 - Run more than one thread using ScheduledExecutorService with same period 使用Runnable和ScheduledExecutorService的内存泄漏 - Memory leak with Runnable and ScheduledExecutorService 使用ScheduledExecutorService同时运行多个线程 - Running multiple threads concurrenty using ScheduledExecutorService 使用 Java mockito 验证 scheduleExecutorService 多次调用 runnable - Verify scheduledExecutorService calls the runnable multiple times using Java mockito 是否可以执行比线程池中的线程更多的请求? - Is it possible to execute more requests than there are threads in thread pool? 使用多于硬件线程的注意事项? - Considerations when using more threads than hardware threads? ScheduledExecutorService:如何等待所有任务完成然后执行更多任务 - ScheduledExecutorService: how to wait for all tasks to finish then execute more tasks java ScheduledExecutorService可运行的异常处理 - java ScheduledExecutorService runnable exception handling ScheduledExecutorService-忽略已运行的可运行文件 - ScheduledExecutorService - Ignore already running runnable 如果将一个可运行对象提交给具有多个线程的执行程序服务,那么多个线程会执行该可运行对象吗? - If you submit one runnable to an executor service with multiple threads, will multiple threads execute that runnable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM