Example: Synchronized and Wait/Notice
class BetterBuffer {
private Object data;
/* synchornized method to Get next data unit. Will put this object's
thread into wait mode if no data exists in buffer.*/
public synchronized Object get() {
while (data==null) {
try { wait(); } catch (InterruptedException e) { }
}
Object get_data = data;
data = null;
notify();
return get_data;
}
/*synchronized method to put data into the buffer that has a
size of 1 unit so, it must wait if their currently already is
data in the buffer for it to be removed via the Get method. If
this is the case with put this object's thread into wait.*/
public synchronized boolean put(Object put_data) {
while (data!=null) {
try { wait(); } catch (InterruptedException e) { }
}
data = put_data;
notify();
return true;
}
}
Note in the above example, that if more that
one thread could perform get()s or put()s concurrently then the
notify() calls should be changed to notifyAll() calls since a notify
from one put()ing thread might happen to wake just another putting
thread, which could therefore not make progress - if there is a
getting thread then we must make sure that it will be woken up.
The while loop and monitor lock will ensure
that only the right thread can keep going - the rest will wait again.
|