Thursday 8 March 2012

Thread synchronization in Java

•When two or more threads access the same resource, we must ensure that only one thread can access the resource at a time. The process which allows this is known as “synchronaization”.
•Java provides support for synchronization.
•The key concept in synchronization is the “monitor” (also called as a semaphore).
•A monitor is an object that is used as an mutually exclusive lock or “mutex”.
•Only one thread can own a monitor at a time.

•A thread that acquires a lock is said to “enter” the monitor. When a thread enters the monitor, no other thread can enter the monitor. All other threads are said to be “waiting” for the monitor.
•Threads can be synchronized in two ways:
1) Using synchronized methods.
2) Using the synchronized statement.

Using synchronized methods:
synchronized method



Using synchronized block:
synchronized block

No comments:

Post a Comment