java concurrency: flag / event
I'm looking for a non-r开发者_JAVA技巧esettable flag or event class in the java concurrency classes, something that I can use to check if something is done and is threadsafe. Ideally something like:
public interface Event
{
/** returns true if signal() has been called */
public boolean hasOccurred();
/** returns when signal() has been called */
public void await();
public void signal();
}
Does something like this exist already? I'm having a brain cramp trying to remember
I think you're looking for a CountDownLatch - in particular, instantiate it with a count of 1.
Then your operations are as follows:
- hasOccurred:
latch.getCount() == 0
- await:
latch.await()
- signal:
latch.countDown()
If you want something you can reset and use repeatably, then a CyclicBarrier may be more what you are looking for. The CountDownLatches, once they've been triggered, cannot be reset.
Edit: It's worth noting that the CountDownLatch is more easily composable to larger operation too than the Event
interface you mentioned. So for instance, if you were going to wait for 4 worker threads to finish, you could give each worker its own event/1-count-latch and wait for each one in turn. It's arguably cleaner, though, to simply create a single CountDownLatch with a count of 4, and share this between all the workers (something that requires no changes to the worker logic at all, and that could not be done as simply with multiple smaller Events).
Do you mean Condition?
class BoundedBuffer {
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
final Object[] items = new Object[100];
int putptr, takeptr, count;
public void put(Object x) throws InterruptedException {
lock.lock();
try {
while (count == items.length)
notFull.await();
items[putptr] = x;
if (++putptr == items.length) putptr = 0;
++count;
notEmpty.signal();
} finally {
lock.unlock();
}
}
public Object take() throws InterruptedException {
lock.lock();
try {
while (count == 0)
notEmpty.await();
Object x = items[takeptr];
if (++takeptr == items.length) takeptr = 0;
--count;
notFull.signal();
return x;
} finally {
lock.unlock();
}
}
}
精彩评论