Synchronized methods and blocks -II

Synchronized Method

Synchronize methods are very useful specially when state of an object is changed by class member method which can corrupt object state if executed concurrently. Consider example discussed in previous article, can be found from here, where class counter have two methods increment and decrement. One thread is incrementing whereas other is decrementing counter. If several threads have to share the same counter, then one thread may not be able to increment counter while another decrementing counter. Integerity of counter is maintained in the face of several threads accessing the state of same counter.

After running program with synchronized method increment() and decrement() avoids race of condition. Method sleep() does not release any lock of current thread. It release lock once synchronized method exits.

public class MExclusion {

	public static void main(String[] args) {
		final Counter count = new Counter();  //  Shared by the threads.

        (new Thread("Increment") {                     //  Thread no. 1
            public void run() {
                for(int i =0; i<10; i++) {
                    System.out.println("Increased : " +
                        count.increment());
                }
            }
        }).start();

        
        (new Thread("Decrement") {                     //  Thread no. 2
            public void run() {
                for(int i =0; i<10; i++) {
                    System.out.println("Decreased : " + count.decrement());
                }
            }
        }).start();

        System.out.println("Exit from main().");
    }

}

class Counter{
	int count;
	
	Counter(){
		count=0;
	}
	public synchronized  int increment(){        //synchronized method
		return count++;
	}
	
	public synchronized  int decrement(){        //synchronized method
		return count--;
	}
}

Possible output is :

Increased : 0
Increased : 1
Increased : 2
Increased : 3
Increased : 4
Increased : 5
Increased : 6
Increased : 7
Increased : 8
Increased : 9
Exit from main().
Decreased : 10
Decreased : 9
Decreased : 8
Decreased : 7
Decreased : 6
Decreased : 5
Decreased : 4
Decreased : 3
Decreased : 2
Decreased : 1

No Responses