Java Thread synchronization - Thread.sleep() Method Not Working as desired

java, multithreading, synchronization

Solution

This is because you have two different instances of `Syncc` in play here. Each thread has its own copy of `Syncc`.

Try doing the same with a single instance. You could also synchronize on the static context and try.

To simulate, modify `Thread1` and `Thread2` to accept an instance of `Syncc`.

public class Thread1 extends Thread {
    private Syncc syncc;

    public Thread1(Syncc syncc) {
        this.syncc = syncc;
    }

    public void run() { 
        this.syncc.me("T1:");
    }   
}

You can then start them as so:

public static void main(String args[]) {
    Syncc syncc = new Syncc();

    Thread1 t1 = new Thread1(syncc);
    Thread2 t2 = new Thread2(syncc);

    System.out.println("going to start t1");
    t1.start();
    System.out.println("going to start t2");
    t2.start();
}

Problem

i heard, sleep() will lock the current sync method/block But here, when i call sleep() on thread 1, thread 2 is able to access the same block? Can anyone Explain? Main.java ``` public class Main { public static void main(String args[]) { Thread1 t1 = new Thread1(); Thread2 t2 = new Thread2(); System.out.println("going to start t1"); t1.start(); System.out.println("going to start t2"); t2.start(); } } ``` ===================================================================== Thread1.java ``` public class Thread1 extends Thread{ public void run() { Syncc s1 = new Syncc(); s1.me("T1:"); } } ``` ===================================================================== Thread2.java ``` public class Thread2 extends Thread{ public void run() { Syncc s2 = new Syncc(); s2.me("T2:"); } } ``` ===================================================================== Syncc.java ``` public class Syncc{ public void me(String s){ synchronized(this){ for(int i=0; i<=5; i++) { System.out.println(s+" "+" "+i); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } ``` ========================================== Output: ``` going to start t1 going to start t2 T2: 0 T1: 0 T2: 1 T1: 1 T1: 2 T2: 2 T1: 3 T2: 3 T1: 4 T2: 4 T2: 5 T1: 5 ``` BUT according to sleep() method, it should not unlock the current synchronization block right? if so the out put should be.. going to start t1 going to start t2 ``` T1: 0 T1: 1 T1: 2 T1: 3 T1: 4 T1: 5 T2: 0 T2: 1 T2: 2 T2: 3 T2: 4 T2: 5 ``` i mean after thread 1 execution only thread 2 should start right? Whats the issue?

Original source