最佳实践:在完成处理队列时停止线程。

huangapple 未分类评论49阅读模式
英文:

Best practice stop thread when finish processing queue

问题

我正在尝试理解最佳实践,以便创建一个线程,确保排队的消息以同步方式执行,并且一旦没有更多消息需要处理,线程就会自行结束。

我已阅读了Handler和ServiceExecutor的文档,并且发现ExecutorService的submit方法返回一个Future对象,我可以从中调用Future.get(),但这样我就需要另一个线程在Runnable的执行完成时得到通知。
另外在Executor的文档中,他们有一个SerialExecutor的示例,在这里我猜我可以检查队列的大小以便结束线程。

老实说,我认为肯定有更好的方法来实现这种行为,所以我想知道什么是最佳实践。

编辑:

我并不是一次性拥有所有的消息,所以我不知道线程何时会停止,除非我想要强制终止它。如果没有特定的条件,我希望它一直运行,直到完成处理所有消息。

英文:

I'm trying to understand which would be the best practice to have a thread which ensures that the messages queued are executed in a synchronous way and it finishes itself once it hasn’t more messages to process.

I've been reading the documentation of Handler and ServiceExecutor and I found ExecutorService's submit method returns a Future object from which I could call Future.get() but then I would need another thread to be noticed when the execution of the Runnable has finished.
Also on Executor's doc they have a SerialExecutor example where I guess that I could check the size of the queue in order to finish the thread.

Honestly I think that there has to be a better way to achieve this behaviour, so I was wondering which is the best practice.

Edit:

I don't have all the messages at once, so I don't know when the thread will stop or until I want to force it to stop. If not, I'd like to keep running until it has finished processing all the messages.

huangapple
  • 本文由 发表于 2020年4月10日 01:47:11
  • 转载请务必保留本文链接:https://java.coder-hub.com/61127125.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定