-, , , . , , . PriorityQueue .
. , . Object.wait(long) , , .
, . , , . Object.notifyAll() , . , , , .
public class ProcessingQueue extends Thread {
private PriorityQueue<Task> tasks;
private volatile boolean isRunning = true;
public void addTask(Task t) {
synchronized (this.tasks) {
this.tasks.offer(t);
// this call requires synchronization to this.tasks
this.tasks.notifyAll();
}
}
public void shutdown() {
this.isRunning = false;
synchronized (this.tasks) {
this.notifyAll();
}
}
public void run() {
while (this.isRunning) {
synchronized (this.tasks) {
Task t = this.tasks.peek();
// by default, if there are no tasks, this will wake every 60 seconds
long millisToSleep = 60000;
// getExecuteMillis() should return the time, in milliseconds, for execution
if (t != null) millisToSleep = t.getExecuteMillis() - System.currentTimeMillis();
if (millisToSleep > 0) {
try {
// this line requires synchronization to this.tasks
// and the lock is removed while it waits
this.tasks.wait(millisToSleep);
} catch (InterruptedException e) {
}
}
t = this.tasks.poll();
if (t != null) {
t.execute();
}
}
}
}
}