scheduleAtFixedRate
沒有什么歧義,很容易理解,就是每隔多少時間,固定執行任務。
scheduleWithFixedDelay 比較容易有歧義
貌似也是推遲一段時間執行任務,但Oracle的解釋如下,delay
的意思是當結束前一個執行后延遲的時間
scheduleWithFixedDelay Parameters:
command
- the task to execute
initialDelay
- the time to delay first execution
delay
- the delay between the termination of one execution and the commencement of the next
unit
- the time unit of the initialDelay and delay parameters
scheduleWithFixedDelay 比如當前一個任務結束的時刻,開始結算間隔時間,如0秒開始執行第一次任務,任務耗時5秒,任務間隔時間3秒,那么第二次任務執行的時間是在第8秒開始。
import java.util.Date; public class WorkerThread implements Runnable{ private String command; public WorkerThread(String s){ this.command=s; } @Override public void run() { System.out.println(Thread.currentThread().getName()+" Start. Time = "+new Date()); processCommand(); System.out.println(Thread.currentThread().getName()+" End. Time = "+new Date()); } private void processCommand() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public String toString(){ return this.command; } }
import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ScheduledThreadPool { public static void main(String[] args) throws InterruptedException { ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); System.out.println("Current Time = "+new Date()); for(int i=0; i<10; i++){ Thread.sleep(1000); WorkerThread worker = new WorkerThread("do heavy processing"); //scheduledThreadPool.schedule(worker, 3, TimeUnit.SECONDS); //scheduledThreadPool.scheduleAtFixedRate(worker, 5, 5, TimeUnit.SECONDS); scheduledThreadPool.scheduleWithFixedDelay(worker, 5, 3, TimeUnit.SECONDS); } Thread.sleep(300000); scheduledThreadPool.shutdown(); while(!scheduledThreadPool.isTerminated()){ } System.out.println("Finished all threads"); } }