Timer

import java.util.Timer;
import java.util.TimerTask;
/**
 * @author Pickle
 * @version V1.0
 * @date 2024/3/12 15:06
 */
public class TimerDemo {
    public static void main(String[] args) {
        //Timer本身也是一个线程
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "执行了一次");
            }
        },3000,2000);
        //Timer是单线程的,当处理多个任务时候,存在延时与设置定时器的时间有出入
        //可能存在某个任务异常,导致后续任务无法正常执行
        
    }
}

ScheduleExecutorService

ScheduleExecutorService是Jdk5引入的并发包,目的是弥补Timer的缺陷,内部使用了线程池。

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

/**
 * @author Pickle
 * @version V1.0
 * @date 2024/3/12 15:15
 */
public class ScheduleExecutorDemo {
    public static void main(String[] args) {
        final ScheduledExecutorService pool = Executors.newScheduledThreadPool(3);
        pool.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "输出");
            }
        },0, 2, TimeUnit.SECONDS);
        pool.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "输出");
            }
        }, 2, TimeUnit.SECONDS);
    }
}