Java中的事件循环(event loop)

在stackoverflow看到的

https://stackoverflow.com/questions/42278328/event-loop-in-java

事件循环就是while(true)

轮询方式

答案完全取决于您在此块中执行的操作:

1
2
3
while (true) {
// check queue and execute any callback...
}

如果某个元素可以用,队列检查到堵塞,则就CPU使用率而言,“最有效”的是轮询方式。如果检查没有阻塞,则调用线程将旋转,并且您将在循环期间以最大容量运行一个硬件线程。但是,这消除了同步成本,并为您提供了绝对最佳的响应时间。下面是一些例子:

阻塞队列(对CPU的负担最少,但以同步为代价)

1
2
3
4
5
6
Queue<T> q = new LinkedBlockingQueue<>();
...
while(true){
T t = q.take();
//t will never be null, do something with it here.
}

非阻塞队列(对CPU的负担最大,但没有同步成本)

1
2
3
4
5
6
7
Queue<T> q = new LinkedList<>();
...
while(true){
T t;
while((t = q.poll()) == null); //busy polling!
//t will never be null, do something with it here
}

ScheduledExecutorService

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html

最后…如果最终使用计划的执行程序服务,则将强制两次轮询之间的非零等待时间。与完整的BlockingQueue实现相比,这在CPU的性能上是同样高效的,但是您还不得不在响应时间上浪费时间,直到调度间隔。对于您的应用程序来说,什么是“最佳”取决于您是否有能力等待两次轮询之间的最短睡眠时间(我认为您可以安排微秒的时间…?),或者是否需要更快的时间来进行繁忙的轮询方案。

这个网站上也讲了https://activej.io/eventloop.html