I am trying to get a lock on the object for 10 seconds. I am expecting any other thread should wait for 10 seconds to use that object as it's synchronized.
Here is the code:
public class Test {
Student student1=new Student(1,"sachin");
Thread thread1 = new Thread("My Thread 1"){
public void run(){
synchronized(student1){
try {
System.out.println("in thread1,acquired student1 and will wait for 10 sec");
sleep(10000);
System.out.println("Leaving the lock on student1");
} catch (InterruptedException e) {
}
}
}
};
Thread thread2 = new Thread("My Thread 2"){
public void run(){
System.out.println(String.valueOf(student1.name) +" "+ student1.roll);
}
};
public class Student {
int roll;
String name;
public Student(int roll,String name)
{
this.name=name; this.roll=roll;
}
}
public static void main(String a[]){
Test test = new Test();
test.thread1.start();
test.thread2.start();
}
}
Output:
in thread1, acquired student1 and will wait for 10 sec
sachin 1
Leaving the lock on student1
Expected output:
in thread1, acquired student1 and will wait for 10 sec
Leaving the lock on student1
sachin 1
I am expecting this because, thread2 shouldn't be able to access the student1 until thread leaves the lock on it.
Thread 2 is not synchronized on student1. That's why it is not waiting. You need to synchronize both threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With