1 Packagetest;2 3 Public classTest1 {4 5 Public Static voidMain (string[] args) {6 7 NewThread (NewThread1 ()). Start ();8 Try {9Thread.Sleep (5000);Ten}Catch(interruptedexception e) { One A e.printstacktrace (); - } - NewThread (Newthread2 ()). Start (); the - } - } - + classThread1ImplementsRunnable { - + @Override A Public voidrun () { at - synchronized(Test1.class) { -System.out.println ("Here is Thread1"); -System.out.println ("Thread1 is Waiting"); - - Try { inTest1.class. Wait ();//calling wait will release the thread lock, enter the waiting lock pool until the Notify method wakes up, and then enter the object lock pool again to get the object lock into the running state. - to}Catch(interruptedexception e) { + - e.printstacktrace (); the } *System.out.println ("Thread1 is going"); $System.out.println ("Thread1 is Over");Panax Notoginseng } - } the } + A classThread2ImplementsRunnable { the + @Override - Public voidrun () { $ // $ synchronized(Test1.class) { -System.out.println ("Here is Thread2"); -System.out.println ("Thread2 is Sleeping"); theTest1.class. Notify (); - Try {WuyiThread.Sleep (4000);//call sleep, will wait for the corresponding time, waiting for the thread lock is not released, the time will go into the running state; theSystem.out.println ("Thread2 is going"); -System.out.println ("Thread2 is Over"); Wu}Catch(interruptedexception e) { - e.printstacktrace (); About } $ } - } -}
Operation Result:
Thread1thread1 is Waitinghere are thread2thread2 are Sleepingthread2 is goingthread2 Is over
Comment out the "test1" of 49 lines. class. Notify (); "
The program will always be in a pending state:
Thread1thread1 is Waitinghere are thread2thread2 are Sleepingthread2 is goingthread2 are over
The sleep () method belongs to the thread class; the wait () method belongs to the object class.
During the call to the sleep () method, the thread does not release the object lock. When the Wait () method is called, the thread discards the object lock, enters the waiting lock pool waiting for the object, and the thread only enters the object lock pool when the Notify () method is called for this object.
Thank the Great God Hongten;
difference between sleep () and Wait () (Java note-multithreading)