Java uses synchronization to help co-ordinate timing
between threads by locking access to the methods for an object.
The keyword
synchronized
indicates that the specified code can only be executed by a one thread of execution on the
object at the same time.
You typically synchronize methods, but can also synchronize a block
of code.
Again: Only one synchronized method or block of code can be run at the
same time for the same object.
Once the method or block starts execution, no other thread can run
that code, or any other synchronized code for that object.
This is true even if the thread is not in the running state (i.e. it's
in ready or blocked on a read, but not true if it is the wait state).
When the synchronized code completes, then another thread can start
running the code.
The syntax for a synchronized method is to add the keyword
synchronized to the signature:
public synchronized void abc()
The syntax for a synchronized block of code is to use
synchronized(obj), followed by the
block of code:
synchronized(object)
{
// statements are synchronized
}
It is typically considered more appropriate to synchronize
methods (better OO), rather than blocks.
It is also a little bit of a different model than other locking
schemes - you don't lock an object directly, but instead lock access
to it by locking the methods.