"Java Multi-threading and Concurrency Library" 4. Traditional thread Synchronous communication technology

Source: Internet
Author: User

We first understand the traditional thread synchronous communication through a face test.

Topic:
The child thread loops 10 times, then the main thread loops 100 times, then goes back to the sub-thread loop 10 times,
Then go back to the main thread and loop 100 times, so loop 50 times, please write the program.

I did not look at the answer, first wrote a piece of code with their own ideas, some of the traditional "producers and consumers" for reference
The multithreaded model is written out:
Package cn.edu.hpu.test;/** * Required Actions: * Sub-thread loop 10 times, then the main thread loop 100 times, and then back to the sub-thread loop 10 times, * then back to the main thread and loop 100 times, so loop 50 times.        * **/public class ThreadTest3 {public static void main (string[] args) {output out =new output ();//Cyclic Output class Note: This is to ensure that the child thread and the main thread class introduce the same output object//or else cannot share two "keys" Mainrunnable main=new mainrunnable (out);//main thread Sonru Nnable son=new sonrunnable (out);//child thread new Thread (son). Start ();//The main thread starts the new thread (main). Start ();//Child thread Start}}    Class output{//Two "key" Static Boolean Mbegin=false;  Static Boolean sbegin=true;//The first time a child thread starts executing, so here defaults to TRUE////The main thread loop printing method (cannot be interrupted) public synchronized void Domainwhile (int num) throws interruptedexception {int i=0;//each time I is initialized to 0 for loop use while (Mbegin==false) {///If the child thread is executing, the main thread waits until the child line Cheng        Key this.wait of the main thread of the complex (); } for (i = 1; I <=100; i++) {//start loop (100 cycles each time in the method) System.out.println ("The main thread executes the first" +i+ "cycle, the total cycle is" +num+ ")            ;            if (i==100) {break;       } if (i==100) {/////main thread loop is finished printing, make way for child thread to execute sbegin=true;//child thread to start working mbegin=false;//main thread stops working This.notify ();//notifies other threads to start working}}//child thread looping printing method (cannot be interrupted) public synchronized void dosonwhile (int num) throws in            terruptedexception {int j=0;//each time I is initialized to 0 for loop use while (Sbegin==false) {//If the main thread is executing, the child thread waits until the main thread resumes the child thread's key        This.wait ();            } for (j = 1; J <=10; J + +) {//Start loop (10 cycles each time in the method) System.out.println ("sub-thread executes the" +j+ "cycle, the total cycle is" +num+ ");            if (j==10) {break;            }} if (j==10) {//Sub-thread loop is finished printing, to give way to the main thread execution sbegin=false;//child threads stop working mbegin=true;//The main thread begins        This.notify ();//notifies other threads to start working}}}class mainrunnable implements runnable{Output out =null;    Mainrunnable (output out) {//The Output object is introduced in This.out=out; } public void Run () {try {////Because to perform 50 required operations, the main thread of each operation is executed 2 times, altogether 50*2=100 times for (int i=1;i< = 100;i++) {Out.domainwhile (I%2==0?I/2: (i+1)/2);        }} catch (Interruptedexception e) {e.printstacktrace ();        }}}class sonrunnable implements runnable{Output out =null;    Sonrunnable (Output out) {this.out=out; } public void Run () {try {////Because to perform 50 required operations, the sub-thread is executed 2 times per operation, altogether 50*2=100 times for (int i=1;i<            =100;i++) {Out.dosonwhile (I%2==0?I/2: (i+1)/2);        }} catch (Interruptedexception e) {e.printstacktrace (); }    }    }

First, I created a loop class, and then I used this loop class for the loop printing operation, and I used a different method for the child thread and the main thread to execute,
One of the main threads of the loop printing method, let it print 100 times, and then the child thread in the loop printing method, let it print 50 times, and use the keyword synchronized
Ensure that the respective methods are not interrupted.
By passing in the common output object to the main thread and the child thread, we can guarantee the common static all variables (the two "keys" inside).

The thread's execution rule is to let the child thread run at first (the main thread actually runs, but the Mbegin variable is blocked by false), and runs its loop 10 times.
method, the values of Sbegin and mbegin are changed and other threads are notified. At this point the child thread is blocked because the Sbegin variable is false and the main thread is true because of the mbegin variable
and start running, the main thread executes its own 100 cycles, changes the values of Sbegin and Mbegin, and notifies other threads. The main thread is at this time because the Mbegin variable is false
While the child thread starts running because the Sbegin variable is true ... This completes a round of cycles.
To ensure that the type of loop to perform 50 control, it is each thread their own for loop, they actually each cycle, each executed two times their own cycle printing method, so
Each of them performs a 50*2=100-cycle printing method on each thread.

The result (the picture is too long to intercept only one of three steps of a loop):


Later, I used the parameter count to derive a cycle of 50 cycles, the result is correct.

But I personally think I just realized this effect, code development new bad, writing a bit of cock silk,
It is also not good to control the way threads run and block (with two global variables mbegin and Sbegin) =_=.

Let's take a look at one of the answers provided by others:
Package Cn.edu.hpu.test;public class ThreadTest4 {public static void main (string[] args) {new ThreadTest4 ().    It ();        } public void Init () {final business business = new Business (); New Thread (New Runnable () {public void run () {f or (int i=0;i<50;i++) {business.                        Subthread (i);                }}). Start (); for (int i=0;i<50;i++) {business.        Mainthread (i); }} Private class Business {Boolean bshouldsub = true;//is equivalent to defining a semaphore that controls who executes the public sy                nchronized void Mainthread (int i) {if (bshouldsub) try {this.wait ();      } catch (Interruptedexception e) {e.printstacktrace ();          } for (int j=1;j<=100;j++) {System.out.println (T            Hread.currentthread (). GetName () + ": i=" + i + ", j=" + j);            } bshouldsub = true;                This.notify (); } public synchronized void subthread (int i) {if (!bshouldsub) try                {this.wait ();                } catch (Interruptedexception e) {e.printstacktrace (); } for (int j=1;j<=10;j++) {System.out.println (thread.currentth            Read (). GetName () + ": i=" + i + ", j=" + j);                            } bshouldsub = false;                    This.notify (); }    }}

The result (also the picture is too long to intercept only one of the three steps of a loop):


In fact, the answer is given in the same way as I write myself, and also create a common class to cycle through the data and give
The child thread and the main thread provide a way to loop the printing, unlike me, they use the same common variable to control
Thread startup and blocking, and I used two, and the answer to the code format and naming are compared specifications, this should be improved.

In addition, in addition to using the methods above, a "and faku" approach to using JDK5 is provided to resolve this issue:
Package Cn.edu.hpu.test;import Java.util.concurrent.executors;import Java.util.concurrent.executorservice;import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.reentrantlock;import    Java.util.concurrent.locks.condition;public class threadtest5{private static lock lock = new Reentrantlock ();    private static Condition subthreadcondition = Lock.newcondition ();    private static Boolean bbhouldsubthread = false;        public static void Main (String [] args) {Executorservice ThreadPool = Executors.newfixedthreadpool (3);                Threadpool.execute (New Runnable () {public void run () {for (int i=0;i<50;i++)                                        {Lock.lock (); try {if (!bbhouldsubthread) subth                        Readcondition.await ();                  for (int j=0;j<10;j++) {          System.out.println (Thread.CurrentThread (). GetName () + ", j=" + j);                        } Bbhouldsubthread = false;                    Subthreadcondition.signal ();                    }catch (Exception e) {} finally                    {Lock.unlock ();        }                }                        }                    });        Threadpool.shutdown ();                                    for (int i=0;i<50;i++) {lock.lock ();                                                    try {if (bbhouldsubthread) subthreadcondition.await (); for (int j=0;j<10;j++) {Sys                    Tem.out.println (Thread.CurrentThread (). GetName () + ", j=" + j);                 } Bbhouldsubthread = true;   Subthreadcondition.signal ();                    }catch (Exception e) {} finally {                Lock.unlock (); }                            }    }}

At this point, we can fully understand what is thread synchronous communication by completing the interview question, which is actually
Threads run at the same time, and then through a number of variables or means to allow threads to alternate between the running,

To achieve our purpose of using multithreading.

Reprint Please specify source: http://blog.csdn.net/acmman/article/details/52774603

"Java Multi-threading and Concurrency Library" 4. Traditional thread Synchronous communication technology

Related Article

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.