First cycle ten times the child thread, the main thread in a loop 20 times, then the child thread loop ten times, the main thread loop 20 times, so the cycle 50 times
1 / * 2 * sub-thread of the first cycle ten times, the main thread in a loop 20 times, then the sub-thread loop ten times, the main thread 20 cycles, so cycle 50 times . 3 * @author LLJ . 4 * . 5 * / . 6 public class {ThreadTest . 7 . 8 public static void main (String [] args) { . 9 Syn SYN = new new Syn (); 10 new new the Thread ( new new the Runnable () { . 11 @Override 12 is public void RUN () { 13 is for ( int I = 0 ; I <50; I ++ ) { 14 syn.child(); 15 } 16 } 17 }).start(); 18 for(int i=0; i<50; i++) { 19 syn.main(); 20 } 21 } 22 } 23 24 class Syn{ 25 private boolean temp = true; 26 public synchronized void main() { 27 if(temp) { 28 try { 29 the this .wait (); // causes the current thread to wait until another thread calls the object's notify () method or the notifyAll () method 30 } the catch (InterruptedException E) { 31 is e.printStackTrace (); 32 } 33 is } 34 is for ( int I = 0; I <20 is; I ++ ) { 35 System.out.println ( "main thread" + I); 36 } 37 [ TEMP = to true ; 38 is the this .notify (); // wakeup waiting on an object single thread monitor. 39 } 40 public synchronized void child() { 41 if(!temp) { 42 try { 43 this.wait(); 44 } catch (InterruptedException e) { 45 e.printStackTrace(); 46 } 47 } 48 for(int j=0; j<10; j++) { 49 System.out.println("子线程"+j); 50 } 51 temp = false; 52 this.notify(); 53 } 54 }