Simple example of Java inter-thread communication

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.