public static void main(String[] args) {
System.out.println("任务两秒后开启");
Timer t = new Timer();
//定时执行任务 表示几秒后执行run方法里面的内容
t.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("任务开启");
}
},2000);
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.println("开始循环任务(间隔1s)");
}
},2000,1000);
}
指定定时器执行固定个任务后结束
复制代码
public static void main(String[] args) {
Timer t = new Timer();
int timeCount = 5;
long delay = 1000;
long period = 1000;
t.schedule(new TimerTask() {
int count = 1;
@Override
public void run() {
if(count >= timeCount){
t.cancel();
}
System.out.println("执行任务:"+count);
count++;
}
},delay,period);
}
模拟实现定时器
复制代码
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
class Task implements Comparable<Task>{
//这个类用来描述任务的
private Runnable runnable;
//执行的任务时间
private long time; //time + System.currentTimeMillis()
public Task(Runnable runnable,long time){
this.runnable = runnable;
this.time = time;
}
public long getTime(){
return time ;
}
public void run() {
runnable.run();
}
//比较规则 执行时间在前的先执行
@Override
public int compareTo(Task o) {
return (int)(this.time - o.time);
}
}
public class MyTimer{
//一个阻塞队列
private BlockingQueue<Task> queue = new PriorityBlockingQueue<>();
//扫描线程
private Thread t = null;
public MyTimer(){
t = new Thread(() -> {
while(true) {
try {
Task task = queue.take();
if (task.getTime() > System.currentTimeMillis()) {
//还没到时间
queue.put(task);
} else {
//执行任务
task.run();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
}
public void schedule(Runnable runnable,long time) throws InterruptedException {
//在这一步加System.currentTimeMillis() 不能在getTime方法中加,不然就会一直大于System.currentTimeMillis()
Task task = new Task(runnable, time+System.currentTimeMillis());
queue.put(task);
}
public static void main(String[] args) throws InterruptedException {
MyTimer m = new MyTimer();
m.schedule(new Runnable() {
@Override
public void run() {
System.out.println("这是任务1");
}
},2000);
m.schedule(new Runnable() {
@Override
public void run() {
System.out.println("这是任务2");
}
},1000);
}
}