亲宝软件园·资讯

展开

Java 定时器的实现 Java 定时器的多种实现方式

卷卷啊 人气:1
想了解Java 定时器的多种实现方式的相关内容吗,卷卷啊在本文为您仔细讲解Java 定时器的实现的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,定时器,Java,定时器实现,下面大家一起来学习吧。

一、前言

定时器有三种表现形式:

JDK 提供了三种常用的定时器实现方式,分别为:

(1)Timer

发现 eureka 中大量使用了 Timer 定时器:

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

Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        // 业务代码
    }
}, 5000, 5000);  // 5s 后调度一个周期为 5s 的定时任务

Timer 的内部构造,如下:

public class Timer {
    // 小根堆,run操作 O(1)、新增 O(logn)、cancel O(logn)
    private final TaskQueue queue = new TaskQueue();
    // 创建另外线程,任务处理,会轮询 queue
    private final TimerThread thread = new TimerThread(queue);
    public Timer(String name) {
        thread.setName(name);
        thread.start();
    }
}

Timer 它是存在不少设计缺陷的,所以并不推荐用户使用:

(2)DelayedQueue 延迟队列

特征如下:

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 延迟后开始执行任务,每 2s 重复执行一次
    }
}

ScheduledThreadPoolExecutor 使用了阻塞队列 DelayedWorkQueue

(4)ScheduledThreadPoolExecutor

线程应该是最常见的实现方案,创建一个线程执行任务即可,举例几个不同的写法,代码如下

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();
                }
            }
        });
    }
}

加载全部内容

相关教程
猜你喜欢
用户评论