關於scheduleAtFixedRate方法與scheduleWithFixedDelay的使用


一、scheduleAtFixedRate方法

    該方法是ScheduledExecutorService中的方法,用來實現周期性執行給定的任務,public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit);

command:是給定的任務

initial:表示第一次開始任務時要延遲的時間

period:表示每次執行此任務要間隔的時間

unit: 是用來指定前兩個的時間單位

    執行次方后,開始計時,在延時結束后開始任務,並開始計算周期,下面分兩種情況介紹

情況一:

    執行任務的時間短,而周期長:這是執行完任務后,會等待周期結束,然后再次開始任務

情況二:

    執行任務的時間長,而周期短;即在任務還未完成時,周期就已經結束,這時不能立馬再開始一個任務,需要等待任務的完成,然后在開始任務,對於這種情況給出運行代碼:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MyscheduleAtFixedRate {

	public static void main(String[] args) {
		// TODO 自動生成的方法存根
		ScheduledExecutorService executor=Executors.newScheduledThreadPool(2);
		System.out.println("X  "+System.currentTimeMillis());
		executor.scheduleAtFixedRate(new MyRunableA_atfix(), 1, 1, TimeUnit.SECONDS);
		System.out.println("Y  "+System.currentTimeMillis());
	}

}
class MyRunableA_atfix implements Runnable{

	@Override
	public void run() {
		// TODO 自動生成的方法存根
		
		System.out.println("begin A "+System.currentTimeMillis());
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO 自動生成的 catch 塊
			e.printStackTrace();
		}
		System.out.println("end A "+System.currentTimeMillis());
	}
}

  運行結果:

X  1493197014282
Y  1493197014297
begin A 1493197015311
end A 1493197017340
begin A 1493197017340
end A 1493197019354
begin A 1493197019354

  這表明了任務一開始,延時1S,然后在周期結束后,等待當前任務的完成,在進行循環任務

二、scheduleAtFixedRate方法

    此方法也是循環執行任務,這個方法的參數意義與scheduleAtFixedRate方法的相同

    此方法設置的周期,開始計時的時間與上個方法不同,它是在任務完成之后開始計時的,表示的是上一個任務與下一個任務之間的時間間隔

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM