对 Java 事件循环库的建议
我正在寻找类似 JavaScript setTimeout
的东西,但带有 Runnable
,具有以下限制:
- 每个超时不需要单独的专用线程。
- 已经开发并经过深思熟虑。
- 甚至可能包括附加功能。 (取消超时?,等待什么?,异步 I/O?)
- 不需要任何 GUI 库。 (Java FX/Swing/AWT 都内置了事件循环)
您有什么建议吗?
编辑:我已经找到了我要找的东西。如果有一个库还包含与非阻塞或异步 I/O 相关的内容,那就更好了。
I am looking for something like the JavaScript setTimeout
, but with a Runnable
, with the following restrictions:
- Does not require individual dedicated threads per timeout.
- Already developed and thought through.
- Maybe even including additional features. (cancel timeout?, wait for something?, async I/O?)
- Does not require any GUI libraries. (Java FX/Swing/AWT all have event loops built in)
Do you have any suggestions?
Edit: I have found what I am looking for. A plus would be if there was a library that also included something related to either non-blocking or asynchronous I/O.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可能正在寻找 ScheduledThreadPoolExecutor :
我不太明白计划的可运行对象和事件循环之间的联系,但也许你会发现什么你正在寻找这个班级。
You're probably looking for ScheduledThreadPoolExecutor :
I don't really understand the link between scheduled runnables and an event loop, but maybe you'll find what you're looking with this class.
您可以使用 java.util.Timer
http://docs .oracle.com/javase/6/docs/api/java/util/Timer.html
http://docs.oracle.com/javase/6/docs/api/java/util/TimerTask.html
您可以设置任务仅运行一次或定期运行。
您还可以停止/取消单个 TimerTask 或所有任务。
You can use java.util.Timer
http://docs.oracle.com/javase/6/docs/api/java/util/Timer.html
http://docs.oracle.com/javase/6/docs/api/java/util/TimerTask.html
You can set the task run only once or periodically.
You can also stop/cancel individual TimerTask or all tasks.
如果您正在寻找 Java 中的简单 Node.js 样式事件循环,ThreadPoolExecutor 是一个好的开始。
查看执行器 ThreadPoolExecutor,特别是 Executors.newSingleThreadExecutor()。这为您提供了一个后台线程(如 Node 事件循环:请参阅 这个问题)您可以向其提交任务。
对于异步 IO,处理阻塞活动的任务需要拆分线程(或执行器)并使用 Future 将结果提交回事件循环。
If you're looking for a simple node.js style event loop in Java, ThreadPoolExecutor is a good start.
Take a look at the Executors factory mentioned in the javadoc for ThreadPoolExecutor, particularly Executors.newSingleThreadExecutor(). This gives you a single background thread (like the Node event loop: see the answer to this question) to which you can submit tasks.
For async IO, tasks handling blocking activity need to split of a Thread (or Executor) and use a Future to submit the result back to the event loop.
我认为 Vert.x 正是您所需要的,它是事件驱动且非阻塞的。
I think Vert.x is what you need, it is event driven and non blocking.
您是否考虑过使用ThreadPoolExecutor
可能对你有用。
Have you thought of using awaitTermination API of ThreadPoolExecutor
might be useful to you.