Sunday, 7 May 2017

15. Synchronization - Class level lock


1. What is Synchronization in Thread – Class level lock
1.       Every class in java has a unique lock which is nothing but class level lock.
2.       If a thread wants to execute, a static synchronized method then thread require class level lock.
3.       Once thread got class level lock then it is allowed execute any static synchronized method of that class.
4.       Once method execution completes automatically, thread releases the lock.
5.       While a thread executing static synchronized method the remaining threads are not allowed to execute static synchronized method of that class simultaneously .
6.       But remaining threads are allowed to execute the following methods simultaneously .
a.       Normal static methods
b.      Synchronized instance method (It require object level lock, not class level lock)
c.       Normal instance method
7.       Class level lock is different from  object level lock, both are not dependent.
public class X {
  static synchronized void m1(){......}
  static synchronized void m2(){......}
  static void m3(){.......}
  static void m4(){.......}
  synchronized  m5(){............}
  m6(){............}
}


class Display {

public static synchronized void wish(String name) {

for (int i = 0; i < 10; i++) {
System.out.println("Good morning " + name);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}


}

class MyThread extends Thread {

Display d;
String name;

MyThread(Display d, String name) {
this.d = d;
this.name = name;
}

public void run() {
Display.wish(name);
}
}

public class ThreadDemo {

public static void main(String[] args) throws Exception {

Display d1 = new Display();
Display d2 = new Display();
MyThread thread1 = new MyThread(d1, "Rama");
MyThread thread2 = new MyThread(d2, "Seetha");
thread1.start();
thread2.start();

}
}

No comments:

Post a Comment

3. Java Program to create Binary Tree