How can I create an “event-driven” background thread in Java?

走远了吗. 提交于 2020-01-01 11:48:09

问题


I like the simplicity of invokeLater() for sending units of work to the AWT EDT. It would be nice to have a similar mechanism for sending work requests to a background thread (such as SwingWorker) but as I understand it, these do not have any sort of event queueing & dispatch mechanism, which is what invokeLater() depends upon.

So instead, I've ended up giving my background thread a blocking queue, to which other threads send messages, and the thread essentially runs a receive loop, blocking until a message arrives.

That, in fact, might be exactly how one would implement EDT-like behavior in a background thread (or would it?). On the other hand, I like the simplicity of a thread that simply dangles there inertly, processing "work droplets" whenever they happen to be dispatched to it from some unseen Event Dispatching Queue in the sky. Does Java provide a way to create such an "event-driven worker thread"? Or is message-queueing the right way to do this, after all? And in a related vein, are there drawbacks to the invokeLater() technique of message-passing?


回答1:


You should take a look at java.util.concurrent, more specifically at Executor's, which are usually just a thread pool that can process a request like this: executor.execute(runnableTask);. If you want a single thread to process all the request, then create your thread with a single thread: executor = Executors.newSingleThreadExecutor()'. There are also ExecutorService's which can return a value when the task is done.




回答2:


The Producer-Consumer Design Patter (which is what you're employing with your blocking queue) is just a different approach to solving a different class of problems; EDT employs the Worker Design Pattern. Take a look at both design patterns and see which one suits your needs best.

  • The Producer-Consumer pattern is generally used when you have multiple threads executing independent tasks separately.
  • The Worker pattern, employed by the EDT, is used to funnel the result of multiple tasks into a single thread (in this case the GUI thread).

Of course, you can take the Producer-Consumer pattern and achieve similar behavior to the Worker pattern if you have a single queue and a single consumer with multiple producers, but that just highlights the flexibility of design patterns. So the point, again, is that choosing a design pattern is based on what works best for your particular situation- there is no particularly wrong choice when the patterns are flexible enough to accommodate the behavior you desire.



来源:https://stackoverflow.com/questions/7044699/how-can-i-create-an-event-driven-background-thread-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!