问题
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