如何创建“事件驱动”? Java中的后台线程? [英] How can I create an "event-driven" background thread in Java?

查看:151
本文介绍了如何创建“事件驱动”? Java中的后台线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢简单的 invokeLater(),用于向AWT EDT发送工作单元。有一个类似的机制可以将工作请求发送到后台线程(例如SwingWorker),但据我所知,这些机制没有任何类型的事件排队&调度机制,这是invokeLater()所依赖的。

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.

事实上,这可能正是人们在后台线程中实现类似EDT的行为(或者它会是什么?)。另一方面,我喜欢简单地悬挂在那里的线程的简单性,只要碰巧从天空中某些看不见的事件调度队列发送到它就处理工作水滴。 Java是否提供了创建这种事件驱动的工作线程的方法?毕竟,消息排队是正确的方法吗?并且在相关的情况下,消息传递的 invokeLater()技术有缺点吗?

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?

推荐答案

你应该看看java.util.concurrent,更具体地说是 Executor ,它们通常只是一个可以处理这样一个请求的线程池: executor.execute(runnableTask); 。如果您希望单个线程处理所有请求,则使用单个线程创建您的线程: executor = Executors.newSingleThreadExecutor()'。还有ExecutorService可以在任务完成时返回一个值。

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.

这篇关于如何创建“事件驱动”? Java中的后台线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆