Similar to EboMike's answer you can use a mechanism similar to wait/notify/notifyAll but geared up for using a Lock
.
For example,
public void doSomething() throws InterruptedException {
lock.lock();
try {
condition.await(); // releases lock and waits until doSomethingElse is called
} finally {
lock.unlock();
}
}
public void doSomethingElse() {
lock.lock();
try {
condition.signal();
} finally {
lock.unlock();
}
}
Where you'll wait for some condition which is notified by another thread (in this case calling doSomethingElse
), at that point, the first thread will continue...
Using Lock
s over intrinsic synchronisation has lots of advantages but I just prefer having an explicit Condition
object to represent the condition (you can have more than one which is a nice touch for things like producer-consumer).
Also, I can't help but notice how you deal with the interrupted exception in your example. You probably shouldn't consume the exception like this, instead reset the interrupt status flag using Thread.currentThread().interrupt
.
This because if the exception is thrown, the interrupt status flag will have been reset (it's saying "I no longer remember being interrupted, I won't be able to tell anyone else that I have been if they ask") and another process may rely on this question. The example being that something else has implemented an interruption policy based on this... phew. A further example might be that your interruption policy, rather that while(true)
might have been implemented as while(!Thread.currentThread().isInterrupted()
(which will also make your code be more... socially considerate).
So, in summary, using Condition
is rougly equivalent to using wait/notify/notifyAll when you want to use a Lock
, logging is evil and swallowing InterruptedException
is naughty ;)