3 回答

TA貢獻2065條經驗 獲得超14個贊
我認為使用 a 并以固定速率安排 a 將獲得最佳java.util.Timer結果。TimerTask
假設您有一個TimerTask在執行時打印出日期的。
public class PrintTimeAndIdTask extends TimerTask {
private int id;
public PrintTimeAndIdTask(int id) {
this.id = id;
}
public void run() {
System.out.println(new Date() + " : " + id);
}
}
然后創建一個計時器并安排任務。每個都有不同的延遲,以便它們在您的首選時間間隔內平均分布。
public static void main(String[] args) {
Timer timer = new Timer();
int taskCount = 10;
int timeIntervalMs = 60000;
int delayBetweenTasks = timeIntervalMs / taskCount;
for (int i = 0; i < taskCount; i++) {
TimerTask timerTask = new PrintTimeAndIdTask(taskCount);
int taskDelay = (long) taskCount * delayBetweenTasks;
timer.scheduleAtFixedRate(timerTask, taskDelay, timeIntervalMs);
}
}
您會看到每 6 秒執行一次任務。
Wed Feb 20 17:17:37 CET 2019 : 0
Wed Feb 20 17:17:43 CET 2019 : 1
Wed Feb 20 17:17:49 CET 2019 : 2
Wed Feb 20 17:17:55 CET 2019 : 3
Wed Feb 20 17:18:01 CET 2019 : 4
Wed Feb 20 17:18:07 CET 2019 : 5
Wed Feb 20 17:18:13 CET 2019 : 6
Wed Feb 20 17:18:19 CET 2019 : 7
Wed Feb 20 17:18:25 CET 2019 : 8
Wed Feb 20 17:18:31 CET 2019 : 9
Wed Feb 20 17:18:37 CET 2019 : 0
Wed Feb 20 17:18:43 CET 2019 : 1
Wed Feb 20 17:18:49 CET 2019 : 2
Wed Feb 20 17:18:55 CET 2019 : 3
....
請記住,Timer默認情況下 a 不作為守護線程運行。如果您沒有在應用程序關閉時明確取消它,它會繼續運行,因此您的應用程序將不會關閉。

TA貢獻1887條經驗 獲得超5個贊
你的意思是這樣嗎?產生一個線程的單個執行程序,該線程本身產生 10 個線程。
private static final int numProcesses = 10;
private static final ExecutorService executorService = Executors.newFixedThreadPool(numProcesses);
public static void main(String[] args)
{
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(Test::spawnTenThreads, 0, 5, TimeUnit.SECONDS);
}
private static void spawnTenThreads()
{
for (int i = 0; i < numProcesses; ++i)
{
final int iteration = i;
executorService.submit(() -> System.out.println(iteration));
}
}
添加回答
舉報