synchronized
indicates a synchronized method.
class counter { private int count = 0; public synchronized void increase() { count++; } public int value() { return count; } }
synchronized (
class-instance) {
code-block }
method void f() { synchronized (this) { // f's body } }
class counter private int counter = 0 public synchronized int increase() System.out.println("counter = " + value() + ".") count++ public synchronized void value() return count
increase()
still holds the lock after the value()
call.
synchronized(obj) { // access obj's fields }
synchronized
.
public synchronized void change_name(String new_name) { // whatever }
public synchronized void down() { // wait until count is positive. count--; }
while (count < 1) { }
?
wait()
, notify()
, and notifyAll()
provide conditional synchronization.
public void wait()
blocks the calling thread in the wait set
wait()
throws Interrupted Exception
s.
public void notify()
unblocks a thread, if any, in the wait set.
public void notifyAll()
unblocks all threads in the wait set.
notify()
unblocks an arbitrary thread in the wait set.
notifyAll()
threads is high.
notify()
may unblock the wrong thread; tends to deadlock.
notifyAll()
is more important than it should be.
if (!buffer_full) wait();
while (!buffer_full) wait();
buffer_full
true.
class buffer private boolean buffer_full = false private Object buffer public synchronized void put(Object o) while (buffer_full) wait() buffer = 0 buffer_full = true notify() public synchronized Object get() while (!buffer_full) wait() Object o = buffer buffer_full = false notify() return o
synchronized
code.
wait()
, notify()
, and notifyAll()
provide conditional
synchronization.
This page last modified on 17 July 2002.