Synchronized methods and blocks -III

Synchronized Blocks

It allows execution of arbitrary code to be synchronized with lock of an arbitrary object. Once a thread reached on synchronized code block after acquiring lock on specified object, other threads will not be able to execute code block or any code requiring same object lock until it is not released by current thread, code block completes normally or uncaught exception is thrown.

public class BExclusion {

	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;
	
	Counter1(){
		count=0;
	}
	public  int increment(){
		synchronized(this){   //synchronized block of code
		return count++;
		}
	}
	
	public  int decrement(){
		synchronized(this){     //synchronized block of code
		return count--;
		}
	}
}

Possible Output is listed as below :
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