5

我想使用 Java 中的执行程序服务以并行方式安排相同的命令。我在线程池执行器上编写了一个包装器,它采用并行计数将命令作为参数调度,并在 for 循环中调度命令(即多次相同的实例)。

这种方法正确吗?有什么建议的方法吗?我正在使用 spring 来创建这些 bean。

4

1 回答 1

3

您可以使用ScheduledExecuterService如下:

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();
    }

}

这将run立即开始每秒执行该方法。

使用这种方法,您可以将其多次添加到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);
于 2012-07-08T13:23:11.573 回答