之前使用Thread/Executor/Fork-Join的多线程三种方式
前一种是立刻执行的,后俩种是框架来进行调度,我们不了解,需要一种定时执行多线程的方式。
定时执行
- 固定某一个时间点一级运行
- 以某一周期
- 简单定时器机制
– 设置计划任务,也就是在指定的时间开始执行某一任务
– TimerTask 用来封装任务 ,也是继承与Runnable接口
– Timer类 定时器
public class TimerTest {
public static void main(String[] args) throws InterruptedException {
MyTask task = new MyTask();
Timer timer = new Timer();
System.out.println("当前时间:"+new Date().toLocaleString());
//当前时间1秒后,每2秒执行一次
timer.schedule(task, 1000, 2000);
Thread.sleep(10000);
task.cancel(); //取消当前的任务
System.out.println("================================");
Calendar now = Calendar.getInstance();
now.set(Calendar.SECOND,now.get(Calendar.SECOND)+3); //当前时间加三秒
Date runDate = now.getTime();
MyTask2 task2 = new MyTask2();
timer.scheduleAtFixedRate