欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java 定時器的多種實現(xiàn)方式

 更新時間:2021年06月07日 08:40:35   作者:卷卷啊  
本文介紹了Java中定時器的多種實現(xiàn)方式,有此需求的朋友可以根據(jù)實際選擇適合自己的方式

一、前言

定時器有三種表現(xiàn)形式:

  • 按固定周期定時執(zhí)行
  • 延遲一定時間后執(zhí)行
  • 指定某個時刻執(zhí)行

JDK 提供了三種常用的定時器實現(xiàn)方式,分別為:

  • Timer
  • DelayedQueue 延遲隊列
  • ScheduledThreadPoolExecutor

(1)Timer

發(fā)現(xiàn) eureka 中大量使用了 Timer 定時器:

  • Timer 屬于 JDK 比較早期版本的實現(xiàn),它可以實現(xiàn)固定周期的任務(wù),以及延遲任務(wù)。
  • Timer 會起動一個異步線程去執(zhí)行到期的任務(wù),任務(wù)可以只被調(diào)度執(zhí)行一次,也可以周期性反復(fù)執(zhí)行多次。

Timer 是如何使用的,示例代碼如下:

Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        // 業(yè)務(wù)代碼
    }
}, 5000, 5000);  // 5s 后調(diào)度一個周期為 5s 的定時任務(wù)
  • TimerTask 是實現(xiàn)了 Runnable 接口的抽象類
  • Timer 負(fù)責(zé)調(diào)度和執(zhí)行 TimerTask

Timer 的內(nèi)部構(gòu)造,如下:

public class Timer {
    // 小根堆,run操作 O(1)、新增 O(logn)、cancel O(logn)
    private final TaskQueue queue = new TaskQueue();
    // 創(chuàng)建另外線程,任務(wù)處理,會輪詢 queue
    private final TimerThread thread = new TimerThread(queue);
    public Timer(String name) {
        thread.setName(name);
        thread.start();
    }
}

Timer 它是存在不少設(shè)計缺陷的,所以并不推薦用戶使用:

  • Timer 是單線程模式,如果某個 TimerTask 執(zhí)行時間很久,會影響其他任務(wù)的調(diào)度。
  • Timer 的任務(wù)調(diào)度是基于系統(tǒng)絕對時間的,如果系統(tǒng)時間不正確,可能會出現(xiàn)問題。
  • TimerTask 如果執(zhí)行出現(xiàn)異常,Timer 并不會捕獲,會導(dǎo)致線程終止,其他任務(wù)永遠(yuǎn)不會執(zhí)行。

(2)DelayedQueue 延遲隊列

特征如下:

  • DelayedQueue 是 JDK 中一種可以延遲獲取對象的阻塞隊列,其內(nèi)部是采用優(yōu)先級隊列 PriorityQueue 存儲對象
  • DelayQueue 中的每個對象都必須實現(xiàn) Delayed 接口,并重寫 compareTogetDelay 方法

DelayedQueue 的使用方法如下:

public class DelayQueueTest {
    public static void main(String[] args) throws Exception {
        BlockingQueue<SampleTask> delayQueue = new DelayQueue<>();
        long now = System.currentTimeMillis();
        delayQueue.put(new SampleTask(now + 1000));
        delayQueue.put(new SampleTask(now + 2000));
        delayQueue.put(new SampleTask(now + 3000));
        for (int i = 0; i < 3; i++) {
            System.out.println(new Date(delayQueue.take().getTime()));
        }
    }
    static class SampleTask implements Delayed {
        long time;
        public SampleTask(long time) {
            this.time = time;
        }
        public long getTime() {
            return time;
        }
        @Override
        public int compareTo(Delayed o) {
            return Long.compare(this.getDelay(TimeUnit.MILLISECONDS), o.getDelay(TimeUnit.MILLISECONDS));
        }
        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(time - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        }
    }
}

(3)ScheduledThreadPoolExecutor

JDK 提供了功能更加豐富的 ScheduledThreadPoolExecutor

public class ScheduledExecutorServiceTest {
    public static void main(String[] args) {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
        executor.scheduleAtFixedRate(() -> System.out.println("Hello World"), 1000, 2000, TimeUnit.MILLISECONDS); // 1s 延遲后開始執(zhí)行任務(wù),每 2s 重復(fù)執(zhí)行一次
    }
}

ScheduledThreadPoolExecutor 使用了阻塞隊列 DelayedWorkQueue。

(4)ScheduledThreadPoolExecutor

線程應(yīng)該是最常見的實現(xiàn)方案,創(chuàng)建一個線程執(zhí)行任務(wù)即可,舉例幾個不同的寫法,代碼如下

4.1.使用thread + runnable

package com.yezi_tool.demo_basic.test;

import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class ThreadTest {

    private Integer count = 0;

    public ThreadTest() {
        test1();
    }

    public void test1() {
        new Thread(() -> {
            while (count < 10) {
                System.out.println(new Date().toString() + ": " + count);
                count++;
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

4.2.使用線程池 + runnable

package com.yezi_tool.demo_basic.test;

import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class ThreadTest {

    private static final ExecutorService threadPool = Executors.newFixedThreadPool(5);// 線程池
    private Integer count = 0;

    public ThreadTest() {
        test2();
    }

    public void test2() {
        threadPool.execute(() -> {
            while (count < 10) {
                System.out.println(new Date().toString() + ": " + count);
                count++;
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

以上就是Java 定時器的多種實現(xiàn)方式的詳細(xì)內(nèi)容,更多關(guān)于Java 定時器的實現(xiàn)的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • MyBatis后端對數(shù)據(jù)庫進(jìn)行增刪改查等操作實例

    MyBatis后端對數(shù)據(jù)庫進(jìn)行增刪改查等操作實例

    Mybatis是appach下開源的一款持久層框架,通過xml與java文件的緊密配合,避免了JDBC所帶來的一系列問題,下面這篇文章主要給大家介紹了關(guān)于MyBatis后端對數(shù)據(jù)庫進(jìn)行增刪改查等操作的相關(guān)資料,需要的朋友可以參考下
    2022-08-08
  • 淺談BeanPostProcessor加載次序及其對Bean造成的影響分析

    淺談BeanPostProcessor加載次序及其對Bean造成的影響分析

    這篇文章主要介紹了淺談BeanPostProcessor加載次序及其對Bean造成的影響分析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • Java狀態(tài)設(shè)計模式實現(xiàn)對象狀態(tài)轉(zhuǎn)換的優(yōu)雅方式

    Java狀態(tài)設(shè)計模式實現(xiàn)對象狀態(tài)轉(zhuǎn)換的優(yōu)雅方式

    Java狀態(tài)設(shè)計模式通過將對象的行為和狀態(tài)分離,使對象能夠根據(jù)不同的狀態(tài)進(jìn)行不同的行為操作。它通過將狀態(tài)抽象成一個獨立的類來實現(xiàn)對狀態(tài)的封裝,從而簡化了復(fù)雜的條件判斷和狀態(tài)轉(zhuǎn)換
    2023-04-04
  • java多線程中線程封閉詳解

    java多線程中線程封閉詳解

    在本文里我們給大家分享了關(guān)于java多線程中線程封閉的知識點內(nèi)容以及用法,有需要讀者們可以參考下。
    2019-07-07
  • Java函數(shù)式編程(一):你好,Lambda表達(dá)式

    Java函數(shù)式編程(一):你好,Lambda表達(dá)式

    這篇文章主要介紹了Java函數(shù)式編程(一):你好,Lambda表達(dá)式,本文講解了新老函數(shù)式編程的一些變化,需要的朋友可以參考下
    2014-09-09
  • Dapr在Java中的服務(wù)調(diào)用實戰(zhàn)過程詳解

    Dapr在Java中的服務(wù)調(diào)用實戰(zhàn)過程詳解

    這篇文章主要為大家介紹了Dapr在Java中的服務(wù)調(diào)用實戰(zhàn)過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-06-06
  • 劍指Offer之Java算法習(xí)題精講二叉樹專題篇下

    劍指Offer之Java算法習(xí)題精講二叉樹專題篇下

    跟著思路走,之后從簡單題入手,反復(fù)去看,做過之后可能會忘記,之后再做一次,記不住就反復(fù)做,反復(fù)尋求思路和規(guī)律,慢慢積累就會發(fā)現(xiàn)質(zhì)的變化
    2022-03-03
  • SpringBoot中如何統(tǒng)一接口返回與全局異常處理詳解

    SpringBoot中如何統(tǒng)一接口返回與全局異常處理詳解

    全局異常處理是個比較重要的功能,一般在項目里都會用到,這篇文章主要給大家介紹了關(guān)于SpringBoot中如何統(tǒng)一接口返回與全局異常處理的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2021-09-09
  • Spring服務(wù)注解有哪些

    Spring服務(wù)注解有哪些

    這篇文章主要介紹了Spring服務(wù)注解,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2016-11-11
  • Java Iterator接口實現(xiàn)代碼解析

    Java Iterator接口實現(xiàn)代碼解析

    這篇文章主要介紹了Java Iterator接口實現(xiàn)代碼解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-05-05

最新評論