package Threadt; public class ThreadMain { public static void main (String args[]) { /span>final Object obj = new Object (); // new
Thread (new thread1to2 (1, obj), "xiaoming" new Thread (new thread1to2 (2, obj), "Xiao Wang" ). Start (); }}
PackageThreadt; Public classThread1to2ImplementsRunnable {Private Final intNumber ; Private intCount = 10; PublicObject obj; PublicThread1to2 (intNumber , Object obj) { This. obj =obj; This. Number =Number ; } Public voidrun () {synchronized(obj) { while(count--> 0) { Try{obj.notify ();//wakes the thread that waits for the RES resource, and gives the lock to the thread (the sync lock completes the auto-release lock)System.out.println (Thread.CurrentThread (). GetName () + "shout:" +Number ); if(Count > 0) obj.wait ();//release the CPU control, release the res lock, this thread is blocked, waiting to be awakened. //If you end to release the lock, it will block the process Else if(count = = 0) obj.notify (); } Catch(interruptedexception e) {e.printstacktrace (); } } } }}
Multithreading wait and notify implementations 1212