HTML Java

Java Object Lock


Object level locking on synchronize method

Example of object locking in java here object s is locked with thread t1 and after completion of t1 then only t2 thread get chance to work on same object .if threads want to enter in synchronized block then its need lock. In the given example object locking in which Synchronized is used in non static method and JVM lock the object intrusively.

Show.java

package DemoThreads;
class Show{
public synchronized void goodMorning(String name) {
for(int i = 0 ;i < 5 ;i++) {
System.out.println("Good Morning "+name);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// public synchronized void goodEvening(){
// System.out.println(“Good mornig”);
// }
/*if suppose there is two synchronize method then when thread t1 lock with the object and enter in goodMorning method and lock it with the object s so still t2 can not go inside the good evening because it needs object but this time ti hold that lock so still t2 will have 2 wait */
}

MyThread.java

class MyThread extends Thread{
Show s;
String name;
MyThread(Show s,String name){
this.s = s;
this.name = name;
}
public void run() {
s.goodMorning(name);
}
}

Threads.java

public class Threads{
public static void main(String args[]) throws
InterruptedException {
Show s = new Show();
MyThread t1 = new MyThread(s,"ankit");
MyThread t2 = new MyThread(s,"agam");
t1.start();
t2.start();
while(t1.isAlive()) {
System.out.println("current state of thread t1 is = "+t1.getState());
System.out.println("current state of thread t2 is = "+t2.getState());
Thread.sleep(2000);
}
}
}

Output

Good Morning ankit
current state of thread t1 is = RUNNABLE
current state of thread t2 is = BLOCKED
Good Morning ankit
current state of thread t1 is = RUNNABLE
current state of thread t2 is = BLOCKED
Good Morning agam
Good Morning agam