![](/img/trans.png)
[英]Java ScheduledExecutorService.scheduleWithFixedDelay starts new thread to execute the task without waiting for 1st task to complete
[英]Using ScheduledExecutorService, How to Start a Thread without waiting for other thread to complete at fixed interval?
我想在每個特定的時間間隔運行任務,而不管以前的線程是否完成。 而且我已將ScheduledExecutorService與計划時間一秒使用。 但是問題是,在我的Runnable中,如果我使線程休眠5秒鍾,則我的ScheduledExecuterService也每5秒執行一次,而它應該在1秒內運行每個線程。
看來ScheduledExecuterService正在等待上一個線程完成。 但是我想,無論任務中的作業等待更長的時間如何,任務都會每1秒觸發一次。
這是我的代碼。
public class MyTask implements Runnable {
public void run() {
System.out.println("hi there at: "+ new java.util.Date());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
這是我的ScheduledExecutorService代碼。
public class JavaScheduledExecutorServiceExample {
public static void main(String[] args) {
ScheduledExecutorService execService = Executors.newScheduledThreadPool(5);
execService.scheduleAtFixedRate(new MyTask(), 0, 1000, TimeUnit.MILLISECONDS);
}
}
糾正我,如果我做錯了。 如果我錯了,是否有其他選擇可以實現相同目標? 提供任何最佳做法可能會更有幫助:)
“ 如果此任務的任何執行花費的時間超過其時間,那么后續執行可能會延遲執行,但不會同時執行。 ”您所看到的行為與javadocs一致
我相信這將按照您指定的方式執行:
public class JavaScheduledExecutorServiceExample {
private static ScheduledExecutorService execService = null;
private static int timesAsleep = 0;
public static class MyTask implements Runnable {
public void run() {
System.out.println("hi there at: "+ new java.util.Date());
// schedule again
execService.schedule(new MyTask(), 1000, TimeUnit.MILLISECONDS);
try {
int i = timesAsleep;
timesAsleep++;
System.out.println("asleep " + i + "----------------------");
Thread.sleep(5000);
System.out.println("awoke " + i + "----------------------");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
execService = Executors.newScheduledThreadPool(5);
execService.schedule(new MyTask(), 1000, TimeUnit.MILLISECONDS);
}
}
注意,在ScheduledExecutorService
實例上使用了schedule()
而不是scheduleAtFixedRate()
。 它還會在開始新任務時安排下一個任務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.