Sunday, 2 March 2014

static Synchronized blocks

synchronized blocks used to take a lock on object, where as static synchronized blocks are used to take a lock on class.

Syntax
synchronized ( ClassName.class ) {
    // body
}

Example
class ClassLockEx implements Runnable{
 static void printMethod(){
  synchronized(ClassLockEx.class){
   for(int i=0; i < 5; i++){
    try{
     Thread.currentThread().sleep(1000);
    }
    catch(Exception e){
     System.out.println(e);
    }
    System.out.println(Thread.currentThread().getName() + " " + i);
   }
  }
 }

 public void run(){
  printMethod();
 }

 public static void main(String args[])throws Exception{
  ClassLockEx obj1 = new ClassLockEx();
  ClassLockEx obj2 = new ClassLockEx();
  Thread t1 = new Thread(obj1);
  Thread t2 = new Thread(obj2);
  t1.start();
  t2.start();
 }
}
 
Output
Thread-0 0
Thread-0 1
Thread-0 2
Thread-0 3
Thread-0 4
Thread-1 0
Thread-1 1
Thread-1 2
Thread-1 3
Thread-1 4
  

static synchronized methods                                                 Inter Thread Communication                                                 Home

No comments:

Post a Comment