"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:
[Java] View plain copy on code to see a snippet derived from my Code slice
Package cn.edu.hpu.test;

/**
* Required Operation:
* 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.
* **/
public class ThreadTest3 {

public static void Main (string[] args) {
Output out =new output ();//Loop Output class
Note: This is to ensure that the child and main thread classes introduce the same output object
Or you won't be able to share two keys.
Mainrunnable main=new mainrunnable (out);//Main thread
Sonrunnable son=new sonrunnable (out);//Sub-thread
New Thread (son). Start ();//main thread start
New Thread (Main). Start ();//Child thread start
}
}

Class output{

Two "keys."
Static Boolean mbegin=false;
Static Boolean sbegin=true;//The first time a child thread starts executing, so this defaults to True

How the main thread loops the print (cannot be interrupted)
Public synchronized void domainwhile (int num) throws Interruptedexception {
int i=0;//Each time I is initialized to 0 for recycling
while (Mbegin==false) {//If a child thread is executing, the main thread waits until the child thread resumes the key of the main thread
This.wait ();
}
for (i = 1; I <=100; i++) {//start loop (100 cycles each time in the method)
SYSTEM.OUT.PRINTLN ("The main thread has executed the first" +i+ "cycle, the total cycle is" +num+ ");
if (i==100) {
Break
}
}
if (i==100) {////main thread loop is finished printing, give way to the child thread to execute
sbegin=true;//Child Threads Start working
mbegin=false;//Main thread stops working
This.notify ();//Notify other threads to start working
}
}

How the child thread loops through the print (cannot be interrupted)
Public synchronized void dosonwhile (int num) throws Interruptedexception {
int j=0;//Each time I is initialized to 0 for recycling
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, make way for the main thread to execute
sbegin=false;//Child Threads Stop working
mbegin=true;//Main thread Start
This.notify ();//Notify other threads to start working
}
}

}

Class Mainrunnable implements runnable{

Output out =null;

Mainrunnable (output out) {//Bring the output object in
This.out=out;
}

public void Run () {
try {
Because to perform 50 required operations, the main thread of each operation will be 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:
[Java] View plain copy on code to see a snippet derived from my Code slice
Package cn.edu.hpu.test;

public class ThreadTest4 {

public static void Main (string[] args) {
New ThreadTest4 (). Init ();
}

public void Init ()
{
Final Business business = new Business ();
New Thread (
New Runnable ()
{

public void Run () {
for (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;//here is the equivalent of defining a semaphore that controls who executes
Public synchronized void Mainthread (int i)
{
if (bshouldsub)
try {
This.wait ();
} catch (Interruptedexception e) {
E.printstacktrace ();
}

for (int j=1;j<=100;j++)
{
System.out.println (Thread.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.CurrentThread (). 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:
[Java] View plain copy on code to see a snippet derived from my Code slice
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 www.zhenlyule.cn
{
private static lock lock = new Reentrantlock ();
private static Condition subthreadcondition = Lock.newcondition ();
private static Boolean bbhouldsubthread = Www.yyzx66.cn/false;
public static void Main (String [] args)
{
Executorservice ThreadPool = Executors.newfixedthreadpool (3);
Threadpool.execute (New Runnable () {
public void www.egouyuLe.cn Run ()
{
for (int i=0;i<50;i++)
{
Lock.lock ();
Try
{
if (!bbhouldsubthread)
Subthreadcondition.await ();
forwww.yinb666.cn (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++)
{
System.out.www.huarenc88.cn/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.

"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.