synchronized MethodsPurpose:
synchronizedis used in multi-threaded programming. Every object withsynchronizedmethods is a monitor. The monitor lets only one thread at a time execute asynchronizedmethod on the object.
Mechanics:
<other modifiers> synchronized <return type> <method name>(<parameter list>) {/* Java statements */
}
Example:
public synchronized void addItem(Object obj) {/* Java statements */
}
Usage:
synchronizedis one of several possible modifiers that can appear anywhere in the space-separated list of modifiers.- A
synchronizedmethod works by locking the object when the method is invoked. If there are severalsynchronizedmethods, only onesynchronizedmethod can be active on an object at once; all other threads attempting to invokesynchronizedmethods must wait. When asynchronizedmethod finishes executing, the lock on the object is released and the monitor lets the highest-priority ready thread attempting to invoke asynchronizedmethod proceed.
Restrictions:
- Unless you are doing multithreaded programming, you do not need
synchronizedmethods.
email suggestions to: cs015tas@cs.brown.edu
