WaitForMultipleObjects in Java

非 Y 不嫁゛ 提交于 2020-01-01 12:15:08

问题


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.


回答1:


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...



回答2:


You can use CountDownLatch object provided by java.util.concurrent package

http://rajendersaini.wordpress.com/2012/05/10/waitformultipleobject-in-java/




回答3:


Just guessing Object.wait(), Object.notify() and Object.notifyAll() would be enough.



来源:https://stackoverflow.com/questions/788835/waitformultipleobjects-in-java

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