Java生产者/消费者,检测处理结束
我正在准备一个应用程序,其中单个生产者生成数百万个任务,然后由可配置数量的消费者处理。从生产者到消费者的通信(可能)将是基于队列的。
从运行生产者/生成任务的线程中,我可以使用什么方法来等待所有任务的完成?我不想恢复任何定期轮询来查看我的任务队列是否为空。无论如何,任务队列为空实际上并不能保证最后的任务已经完成。这些任务可能运行时间相对较长,因此队列很可能是空的,而消费者线程仍在愉快地处理。
Rgds,马丁
I'm preparing an application where a single producer generates several million tasks, which will then be processed by a configurable number of consumers. Communication from producer to consumer is (probably) going to be queue-based.
From the thread that runs the producer/generates the tasks, what method can I use to wait for completion of all tasks? I'd rather not resume to any periodic polling to see if my tasks queue is empty. In any case, the task queue being empty isn't actually a guarantee that the last tasks have completed. Those tasks can be relatively long-running, so it's quite possible that the queue is empty while the consumer threads are still happily processing.
Rgds, Maarten
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能想查看 java.util.concurrent 包。
执行器框架已经提供了执行的方法通过线程池执行任务。
Future
抽象允许等待任务完成。将两者放在一起可以让您轻松协调执行,解耦任务、活动(线程)和结果。
示例:
编辑:使用
CountDownLatch
的替代版本在您的任务中:
You might want to have a look at the java.util.concurrent package.
The executor framework already provides means to execute tasks via threadpool. The
Future
abstraction allows to wait for the completition of tasks.Putting both together allows you coordinate the executions easily, decoupling tasks, activities (threads) and results.
Example:
Edit: Alternative Version using
CountDownLatch
And inside your tasks:
您想知道每个任务完成的位置。我会有另一个已完成的任务报告队列。 (每个任务一个对象/消息)当此计数达到您创建的任务数时,它们已全部完成。该任务报告还可以包含该任务的任何错误和时间信息。
You want to know where every tasks completes. I would have another queue of completed task reports. (One object/message per task) When this count reaches the number of tasks you created, they have all completed. This task report can also have any errors and timing information for the task.
您可以让每个消费者在出队时检查队列是否为空,如果是,则脉冲主线程正在等待的 condvar(或监视器,因为我相信这就是 Java 所拥有的)。
让线程检查全局布尔变量(标记为易失性)是让线程知道它们应该停止的一种方法。
You could have each consumer check to see if the queue is empty when they dequeue, and, if it is, pulse a condvar (or a Monitor, since I believe that's what Java has) on which the main thread is waiting.
Having the threads check a global boolean variable (marked as volatile) is a way to let the threads know that they should stop.
您可以对每个线程使用 join() 方法..这样,直到所有线程都完成后,您的主线程才会结束!通过这种方式,您实际上可以找出所有线程是否已完成!
You can use join() method for each thread ..so that till all the threads are done your main thread will not end! And by this way you can actually find out whether all the threads are done or not!