[英]Submitting the same (Runnable) command multiple times to executor service in Java
我想使用Java中的執行器服務以並行方式安排相同的命令。 我在線程池執行器上編寫了一個包裝器,它將並行計數作為參數調度命令,並在for循環中調度命令(即多次執行相同的實例)。
這種方法是否正確? 有沒有建議的方法這樣做? 我用spring來創建這些bean。
您可以使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.