就是按照时间顺序执行Task那道题,我收集了一些答案自己写了一下,
还请大牛多多多多的指点下,有没有问题。
多谢,多谢!
public class ProcessingQueueTest extends Thread {
//用个minHeap存Tasks
private Queue<Task> Tasks = new PriorityQueue<>(new Comparator<Task>(){
public int compare(Task a, Task b) {
if (a.time < b.time) return -1;
else if (a.time > b.time) return 1;
else return 0;
}
});
private boolean isRunning = true;
// 加Task进Heap
public void addTask(Task task) {
synchronized (this.Tasks) {
Tasks.add(task);
this.Tasks.notifyAll();
}
}
// 停止run
public void stopRunning() {
synchronized (this.Tasks) {
isRunning = false;
this.Tasks.notifyAll();
}
}
// run函数
public void run() {
while (isRunning) {
synchronized (this.Tasks) {
try {
long sleepTime = 6000;
if (!Tasks.isEmpty()) {
sleepTime = Tasks.peek().getExecuteMillis() - System
.currentTimeMillis();
}
if (sleepTime > 0) {
this.Tasks.wait(sleepTime);
}
} catch (InterruptedException ex) {
Logger.getLogger(ProcessingQueueTest.class.getName()).
log(Level.SEVERE, null, ex);
}
if (!this.Tasks.isEmpty()) {
Tasks.poll().execute();
}
}
}
}
}
No comments:
Post a Comment