Thread Communication
I. Conditions for communication between threads
1, more than two threads accessing the same piece of memory
2, thread synchronization, keyword synchronized
Two, the main method of communication between the threads
Wait (); ----> For blocking processes
Notify (); ----> For wake-up processes
Notifyall (); ----> to wake up all processes
Three, the diagram of the thread communication
Iv. instance code for thread communication
1 //Main Thread2 Public classThreadMain {3 4 Public Static voidMain (string[] args)throwsinterruptedexception {5Buffer buffer =NewBuffer ();6 7Thread_one Thread_one =Newthread_one (buffer);8Thread_one.start ();//start a child thread9 TenThread.Sleep (1000);//main thread sleep 1 seconds One AString name =Thread.CurrentThread (). GetName (); - System.out.println (name); -Buffer.donotify ();//Wake up Child Threads the } -}
1 //the memory area to access2 Public classBuffer {3 4 //for Packaging5 Public synchronized voiddowait () {6 Try {7 wait ();8}Catch(interruptedexception e) {9 //TODO auto-generated Catch blockTen e.printstacktrace (); One } A } - Public synchronized voiddonotify () { - notify (); the } -}
1 //Child Threads2 Public classThread_oneextendsthread{3 Privatebuffer buffer;4 Publicthread_one (buffer buffer) {5 This. Buffer =buffer;6 }7 @Override8 Public voidrun () {9 //Child thread SleepTen buffer.dowait (); One //specific action, display the current thread name AString name =Thread_one.currentthread (). GetName (); - System.out.println (name); - } the}
Simple instance of communication between Java threads