java - why the results is 200 and then 100? -


this question has answer here:

class implements runnable {     static int b = 10;      public void run() {         m1();     }      public synchronized void m1() {         b = 100;         try {             thread.sleep(100);         } catch (interruptedexception e) {             e.printstacktrace();         }         system.out.println(b);     }      public synchronized void m2() {         try {             thread.sleep(100);         } catch (interruptedexception e) {             e.printstacktrace();         }         b = 200;         system.out.println(b + "m2");      }      public static void main(string[] args) {         aa = new a();         thread tt = new thread(aa);         tt.start();         aa.m2();     } } 

in aa.m2 main thread call m2 method directly, first executed, because thead tt takes little time initialize , start. m2 method synchronized acquire lock of object aa, when thread tt has finished initializing call m1 method , wait lock of object aa released (m1 method synchronized).


Comments