WaitForMultipleObjects in Java

What will be the most elegant way to implement the Win32 WaitForMultipleObjects equivalent in Java (v6). The thread drops until one of several events occurs. When this happens, I want to process it and fall asleep again. No data required, just an event.

+3
source share
3 answers

It really depends on what you want to do with it, but you can do something as simple as using wait / notify methods or using structures in the java.util.concurrency package. The latter would personally be my choice. You could easily set up a BlockingQueue so that you can have event object makers and block users when events are deleted.

// 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...
+5
source

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

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

0
source

Object.wait(), Object.notify() Object.notifyAll() .

-1

Source: https://habr.com/ru/post/1707104/


All Articles