Java Programming/Keywords/synchronized
From Wikibooks, open books for an open world
synchronized is a keyword.
It marks a 'critical section'. A 'critical section' is where one and only one thread is executing. So to enter into the marked code the threads are 'synchronized', only one can enter, the others have to wait. For more information see Synchronizing Threads Methods or [1].
The synchronized keyword can be used in two ways:
- Mark a method
synchronized - Create a
synchronizedblock
Syntax to mark a method synchronized:
publicsynchronizedvoidmethod() { // Thread.currentThread() has a lock on this object. ie. a synchronized method is the same as calling {synchronized(this){..}}. }
Syntax to mark a synchronized block:
synchronized ( <object_reference> )
{
// Thread.currentThread() has a lock on object_reference. All other threads trying to access it will be blocked until the current thread releases the lock.
}
This page may need to be