2021-03-18 分類: 網站建設
ScheduledExecutorService,是基于線程池設計的定時任務類,每個調度任務都會分配到線程池中的一個線程去執行,也就是說任務是并發執行互不影響。
需要注意:只有當調度任務來的時候,ScheduledExecutorService才會真正啟動一個線程,其余時間ScheduledExecutorService都是出于輪詢任務的狀態。

1、線程任務
class MyScheduledExecutor implements Runnable {
private String jobName;
MyScheduledExecutor() {
}
MyScheduledExecutor(String jobName) {
this.jobName = jobName;
}
@Override
public void run() {
System.out.println(jobName + " is running");
}
}
2、定時任務
public static void main(String[] args) {
ScheduledExecutorService service = Executors.newScheduledThreadPool(10);
long initialDelay = 1;
long period = 1;
// 從現在開始1秒鐘之后,每隔1秒鐘執行一次job1
service.scheduleAtFixedRate(new MyScheduledExecutor("job1"), initialDelay, period, TimeUnit.SECONDS);
// 從現在開始2秒鐘之后,每隔2秒鐘執行一次job2
service.scheduleWithFixedDelay(new MyScheduledExecutor("job2"), initialDelay, period, TimeUnit.SECONDS);
}
ScheduledExecutorService 中兩種最常用的調度方法 ScheduleAtFixedRate 和 ScheduleWithFixedDelay。ScheduleAtFixedRate 每次執行時間為上一次任務開始起向后推一個時間間隔,即每次執行時間為 :initialDelay, initialDelay+period, initialDelay+2*period, …;ScheduleWithFixedDelay 每次執行時間為上一次任務結束起向后推一個時間間隔,即每次執行時間為:initialDelay, initialDelay+executeTime+delay, initialDelay+2*executeTime+2*delay。由此可見,ScheduleAtFixedRate 是基于固定時間間隔進行任務調度,ScheduleWithFixedDelay 取決于每次任務執行的時間長短,是基于不固定時間間隔進行任務調度。
本文題目:【教程】如何使用ScheduledExecutorService?
網頁路徑:http://www.js-pz168.com/news31/105381.html
成都網站建設公司_創新互聯,為您提供虛擬主機、網站設計公司、品牌網站制作、網站制作、微信小程序、網站導航
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯
猜你還喜歡下面的內容