简体   繁体   中英

Submitting the same (Runnable) command multiple times to executor service in Java

I want to schedule the same command in a parallel fashion using executor service in Java. I wrote a wrapper over thread pool executor, which takes the parallel count to schedule the command as parameter and in a for loop, schedules the command(ie same instance multiple times).

Is this approach correct? Is there any suggested way of doing this? I am using spring to create these beans.

You could use the ScheduledExecuterService as follows:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorTest {

    private final static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public static void main(final String[] args) throws InterruptedException {
        scheduler.scheduleAtFixedRate(new Runnable() {
            public void run() {
                System.out.println("executed");
            }
        }, 0, 1, TimeUnit.SECONDS);


        Thread.sleep(10000);
        scheduler.shutdownNow();
    }

}

This will execute the run method every second starting immediately.

With this approach you can add it multiple times to the scheduledExecuterService :

Runnable command = new Runnable() {
    public void run() {
        System.out.println("executed");
    }
};
scheduler.scheduleAtFixedRate(command, 0, 1, TimeUnit.SECONDS);
scheduler.scheduleAtFixedRate(command, 0, 1, TimeUnit.SECONDS);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM