Java中的WaitForMultipleObjects [英] WaitForMultipleObjects in Java

查看:136
本文介绍了Java中的WaitForMultipleObjects的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java(v6)中实现Win32等价的WaitForMultipleObjects的最优雅的方法是什么。线程正在睡眠,直到发生几个事件中的一个。当这种情况发生时,我想要处理它,并回到睡眠。

What would be the most elegant way to implement a Win32 equivalent of WaitForMultipleObjects in Java (v6). A thread is sleeping until one of several events occur. When that happens, I want to process it and get back to sleep. No data is required, just an event.

推荐答案

这取决于你想要做什么,但你可以做一些事情就像使用wait / notify方法一样简单,或者可以使用java.util.concurrency包中的结构。后者本人就是我的选择。你可以很容易地设置一个BlockingQueue,你可以让生产者删除事件对象和消费者阻塞删除事件。

It really depends what you want to do with it, but you could do something as simple as using the wait/notify methods or you could use the structures in the java.util.concurrency package. The latter would personally be my choice. You could easily set up a BlockingQueue that you could have producers drop event objects into and consumers blocking on removing the events.

// somewhere out there
public enum Events {
  TERMINATE, DO_SOMETHING, BAKE_SOMETHING
}

// inside consumer
Events e;
while( (e = queue.take()) != TERMINATE ) {
  switch(e) {
    case DO_SOMETHING:
      // blah blah
  }
}

// somewhere else in another thread
Events e = BAKE_SOMETHING;
if( queue.offer(e) )
   // the queue gladly accepted our BAKE_SOMETHING event!
else
   // oops! we could block with put() if we want...

这篇关于Java中的WaitForMultipleObjects的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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