我有一个活套线程来执行任务。其他线程可以向这个活套线程提交任务。有些任务是直接的任务,另一些是未来的任务,这些任务将在提交后的T秒后执行。我使用PriorityBlockingQueue存储任务,其中使用时间作为优先级,因此队列中的第一个任务是最迫切要执行的任务。
活套的主回路是这样的:
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()。哪一个最适合这里?
发布于 2015-01-26 06:49:57
j.u.c.包包含DelayedQueue,可以满足您的问题。每个排队的对象都应该使用getDelay(.)实现延迟接口方法。
发布于 2015-01-26 06:28:27
你不需要这么做。
BlockingQueue的全部要点是它已经为您管理线程同步。您不需要通知其他线程现在有新的东西可用。
只管用
taskQueue.take(); // blocks until something is there或
taskQueue.poll(1, SECONDS); // wait for a while then give up对于不应该立即处理的“未来任务”,我根本不会将它们添加到此队列中。一旦时间到了(实际上是第二个队列),您可以使用ScheduledExecutorService将它们添加到任务队列中。
想想看,您可以完全取消BlockingQueue,只需在所有任务中使用ScheduledExecutorService (由单个线程支持)。
https://stackoverflow.com/questions/28145541
复制相似问题