Java多线程中的定时器(java.util.Timer)有定时执行任务的功能,通过设定定时器的间隔时间,会自动在此间隔后执行预先安排好的任务(java.util.TimerTask)。
timer.schedule(TimerTask,delay,interval time)
第一个参数是需要执行的任务。此类的类型为java.util.TimerTask。第二个参数是执行任务前等待时间,第三个参数是间隔时间(单位为毫秒)
package timer;
import java.util.concurrent.PriorityBlockingQueue;
public class MyTimer {
PriorityBlockingQueue<MyTimerTask> queue = new PriorityBlockingQueue<>();
Worker worker;
private static class Worker extends Thread {
PriorityBlockingQueue<MyTimerTask> queue;
Worker(PriorityBlockingQueue<MyTimerTask> queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
try {
MyTimerTask task = queue.take();
long current = System.currentTimeMillis();
if (task.delay <= current) {
task.target.run();
} else {
queue.put(task);
Thread.sleep(task.delay - current);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
MyTimer() {
worker = new Worker(queue);
worker.start();
}
void execute(Runnable target, long delay) {
queue.put(new MyTimerTask(target, delay));
}
public static void main(String[] args) {
MyTimer timer = new MyTimer();
timer.execute(new Runnable() {
@Override
public void run() {
System.out.println("该起床了");
}
}, 2000);
System.out.println("另一个人");
}
}
package timer;
public class MyTimerTask implements Comparable<MyTimerTask> {
Runnable target;
long delay;
MyTimerTask(Runnable target, long delay) {
this.target = target;
this.delay = System.currentTimeMillis() + delay;//延时后的时刻
}
@Override
public int compareTo(MyTimerTask o) {
if (delay == o.delay) {
//延时后的时刻
return 0;
} else if (delay < o.delay) {
return -1;
} else {
return 1;
}
}
}
来源:51CTO
作者:凉白开dream
链接:https://blog.51cto.com/14232658/2470169