This example is on-line Rotten Street, sub-thread loop 100 times, the main thread loop 50 times, but I tried many times, and from the Internet to find a lot of examples, actually run more than a few times, see the output is not correct. I don't know if I turned Niu Jiao Jian, or what happened. Nor did the great God ask, so painful. Now record here, wait for time to see later.
Importjava.util.concurrent.locks.Condition;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock; Public classthreadcommunication { Public Static voidMain (string[] args) {FinalTest2 T =NewTest2 (); NewThread (NewRunnable () { Public voidrun () { for(inti=0;i<10;i++) {t.sub (i); }}). Start (); for(inti=0;i<10;i++) {t.main (i); } }}classtest{BooleanIssub =false; Public synchronized voidSubintl) {System.out.println ("-----Sub"); while(!issub) { Try { This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); } } for(inti=0;i<10;i++) {System.out.println (l+ "Sub" +i); } issub=false; This. Notify (); } Public synchronized voidMainintl) {System.out.println ("-----Main"); while(issub) {Try { This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); } } for(inti=0;i<10;i++) {System.err.println (l+ "main" +i); } issub=true; This. Notify (); }}
Java multithreaded Learning-synchronous thread communication