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

后端 未结 3 618
小蘑菇
小蘑菇 2020-12-19 17:13

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?

M

3条回答
  •  情歌与酒
    2020-12-19 18:06

    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();
    }
    

提交回复
热议问题