/*** Test thread's wait notify Notifyall sleep interrupted *@authorTomsnail * @date April 20, 2015 PM 3:20:44*/ Public classTest1 {/*** Object Lock *@authorTomsnail * @date April 20, 2015 PM 3:14:13*/ Private Static FinalObject LockObject =NewObject (); /*** Waiting thread *@authorTomsnail * @date April 20, 2015 PM 3:14:22*/ Static classThread1Implementsrunnable{@Override Public voidrun () {synchronized(lockobject) {Try{System.out.println (Thread.CurrentThread (). GetName ()+ "Wait Start"); Lockobject.wait (); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "Wait End"); } } } /*** Wake-up thread *@authorTomsnail * @date April 20, 2015 PM 3:14:36*/ Static classThread2Implementsrunnable{@Override Public voidrun () {synchronized(lockobject) {lockobject.notify (); System.out.println (Thread.CurrentThread (). GetName ()+ "Notify"); } } } /*** Wake up all threads *@authorTomsnail * @date April 20, 2015 PM 3:14:51*/ Static classThread3Implementsrunnable{@Override Public voidrun () {synchronized(lockobject) {lockobject.notifyall (); System.out.println (Thread.CurrentThread (). GetName ()+ "Notifyall"); } } } /*** Sleep thread *@authorTomsnail * @date April 20, 2015 PM 3:20:30*/ Static classThread4Implementsrunnable{@Override Public voidrun () {Try{System.out.println (Thread.CurrentThread (). GetName ()+ "Sleep"); Thread.CurrentThread (). Sleep (20000); } Catch(interruptedexception e) {System.out.println (Thread.CurrentThread (). GetName ()+ "Interrupted"); } } } Public Static voidMain (string[] args) {Thread T1=NewThread (NewThread1 ()); Thread T3=NewThread (NewThread1 ()); Thread T4=NewThread (NewThread1 ()); Thread T2=NewThread (NewThread2 ()); Thread T5=NewThread (NewThread3 ()); //3 Waiting threads to runT1.start (); T3.start (); T4.start (); Try{Thread.CurrentThread (). Sleep (2000); } Catch(interruptedexception e) {e.printstacktrace (); } //Wake-up thread runT2.start (); Try{Thread.CurrentThread (). Sleep (2000); } Catch(interruptedexception e) {e.printstacktrace (); } //Wake all threads to runT5.start (); //Sleep ThreadThread T6 =NewThread (NewThread4 ()); T6.start (); Try{Thread.CurrentThread (). Sleep (2000); } Catch(interruptedexception e) {e.printstacktrace (); } //Sleep thread InterruptT6.interrupt (); }}
Results
thread-0wait startthread-2wait startthread-1wait startthread-3notifyThread- 0wait endthread-4notifyAllThread-1wait endthread-2wait endthread- 5sleepThread-5interrupted
Re-learn Java Basics (vii): Wait for thread, notify, Notifyall, sleep