我有一个looper线程来执行任务。其他线程可以向此循环线程提交任务。有些任务是即时任务,有些是未来任务,将在提交后T秒后执行。我使用PriorityBlockingQueue
来存储任务,其中时间被用作优先级,因此队列的第一个任务是最迫切需要执行的任务。
looper的主要循环是同伴:
PriorityBlockingQueue<Event> taskQueue = ...
while (true) {
if (taskQueue.isEmpty())
<something>.wait(); // wait indefinitely
else
<something>.wait(taskQueue.peek().time - NOW()); // wait for the first task
Task task = taskQueue.poll(0); // take the first task without waiting
if (task != null && task.time <= NOW())
task.execute();
else if (task != null)
taskQueue.offer(task); // not yet runnable, put it back
}
looper提供允许其他线程(或其自身)提交任务:
public void submitTask (Task task) { // time information is contained in the task.
taskQueue.offer(task);
<something>.signal(); // informs the loop thread that new task is avaliable.
}
在这里,我只有一个线程调用wait()
,多个线程调用signal()
。我的问题是我应该在<something>
的位置使用什么同步原语。 java.util.concurrent
和java.util.concurrent.lock
包中有很多原语。还有synchronized
关键字和Object.wait()/notify()
。哪一个最适合这里?
答案 0 :(得分:1)
你不需要做任何这些。
BlockingQueue的重点在于它已经为您管理了线程同步。您不需要通知其他线程现在有新功能。
只需使用
taskQueue.take(); // blocks until something is there
或
taskQueue.poll(1, SECONDS); // wait for a while then give up
为了您未来的任务&#34;不应该立即处理,我根本不会将它们添加到此队列。一旦时间(实际上是第二个队列),您可以使用ScheduledExecutorService将它们添加到任务队列。
想想看,你可以完全取消BlockingQueue,只需使用ScheduledExecutorService(由单个线程支持,你的&#34; looper&#34;)来完成你的所有任务。
答案 1 :(得分:0)
j.u.c。包含DelayedQueue,可以满足您的问题。 每个排队的对象都应该使用getDelay(..)方法实现Delayed接口。