Synchronous communication between threads

Source: Internet
Author: User

We all know that the code form of the thread in Java can be written as follows

New Thread (New Runnable () {@Overridepublic void Run () {//TODO auto-generated Method stub}}). Start ();
Under Multi-threaded startup, the running between the threads will be randomly switched, usually sometimes, we may need the business requirements of the orderly switch between the execution, to ensure business quasi-cutting, such as the bank pick-up machine, as well as train tickets, in this case, we want to control the communication between the threads, Need to be implemented by a synchronous lock

For example I want thread A to execute 5 thereafter, thread B executes 10 times, or vice versa, so 50 times.

Now let's look at the code

Class business{  Private Boolean bshouldsub = true;  Public synchronized void Sub (int. i) {  while (!bshouldsub) {try {this.wait ()} catch (Interruptedexception e) {//TODO Auto-generated catch Blocke.printstacktrace ();}}  for (int  j=0;j<=i;j++) {System.out.println ("Sub Thread------------------------------------------------------------"+j);}  Bshouldsub = false; This.notify ();  synchronized void Main (int i) {  while (bshouldsub) {try {this.wait ()} catch (Interruptedexception e) {// TODO auto-generated catch Blocke.printstacktrace ();}} for (int j = 0; J <= I; j + +) {System.out.println ("main thread sequence of   " + j+ "   i=" + i);} Bshouldsub = True;this.notify (); }   }
Separate the business of proportionality into one class to ensure the uniqueness of the lock.

Private Boolean bshouldsub = true; is for communication between threads.

Let's look at the execution code of the thread

Final Business business = new Business (), New Thread (new Runnable () {@Overridepublic void Run () {for (int i=0;i<=50;i++) { Business.sub (5);}}). Start (); for (int i = 0; I <=; i++) {business.main (10);}}

At this point, it must be a beginner's understanding of the thread communication mechanism will be further





Synchronous communication between 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.