标签:设定 print queue current end read 功能 static str
Java多线程中的定时器(java.util.Timer)有定时执行任务的功能,通过设定定时器的间隔时间,会自动在此间隔后执行预先安排好的任务(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;
}
}
}
标签:设定 print queue current end read 功能 static str
原文地址:https://blog.51cto.com/14232658/2470169