Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

synchronized block not blocking the object

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.

like image 855
Sriharsha g.r.v Avatar asked Dec 20 '25 21:12

Sriharsha g.r.v


1 Answers

Thread 2 is not synchronized on student1. That's why it is not waiting. You need to synchronize both threads.

like image 148
StenSoft Avatar answered Dec 23 '25 11:12

StenSoft