I heard sleep () will block the current method / sync block. But here, when I call sleep () on thread 1, thread 2 can 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(); } } } } }
============================================
Conclusion:
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 the sleep () method, it should not immediately block the current synchronization block? if so, then there should be a way out ..
starts t1 starts 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 means that after thread 1 is executed, only thread 2 should start right? What is the problem?
source share