Communication between threads------------waiting for wakeup mechanism

Source: Internet
Author: User
Tags stub
Communication between threads
The synchronization thread must meet two conditions:
One: two or more threads of more than two
Two: all use the same lock object


Topic Description:
First of all, there is a resource pool (Resource), input thread (input) continues to add content to the resource pool, output thread (outputs) continuously output content
and two threads need to be synchronized. The desired result is that the input thread enters a content and then immediately outputs the thread to read a content.

The first time you write code, you do not use synchronization, nor do you use the wait-wake mechanism

/** * Communication between Threads:--------waiting for Wake mechanism * Topic Description: * First by a resource pool (Resource), input thread (input) continuously to the resource pool to add content, output thread (outputs) continuously output content * and two lines
	The process needs to be synchronized * * */class resource{String name;
String sex;
	Class Input implements runnable{Boolean inputflag=false;
	Resource R;
	Input (Resource r) {THIS.R = R; @Override public void Run () {//TODO auto-generated method stub while (true) {if (Inputflag) {r.name = "mik
				E ";
				R.sex = "Man";
			Inputflag = false;
				else {r.name = "Lili";
				R.sex = "female";
			Inputflag = true;
	Class Output implements runnable{Resource R;
	Public Output (Resource r) {THIS.R = R; @Override public void Run () {//TODO auto-generated method stub while (true) {System.out.println (r.name+ "-----")
		+r.sex); 
		}} public class Threadsynchronized {public static void main (string[] args) {//TODO auto-generated a stub
		Resource r = new Resource ();
		Input in = new input (r);
		
		Output out = new output (r); ThreadT1 = new Thread (in);
		
		Thread t2 = new Thread (out);
		T1.start ();
	T2.start (); }

}


"Mike------Girl" and "Lili------man" obviously feel strange.
Explanation Reason: When the input thread does not finish the input, the output thread grabs the CPU and executes the output thread directly, which is why the above strange phenomenon
Solution: Join thread synchronization to synchronize the input and output threads. When the resource is operated on, only the input thread completes the assignment and the output line Chengyu can perform

The code after joining the thread synchronization block is as follows:


/* Communication between Threads:--------Waiting for Wake mechanism topic Description: First by a resource pool (Resource), input thread (input) continuously to the resource pool to add content, output thread (outputs) continuously output content and two threads need to sync
	* */class resource{String name;
	String sex;  Boolean flag = false;
	The token is initially false} class Input implements runnable{Boolean inputflag=false;
	Resource R;
	Input (Resource r) {THIS.R = R; @Override public void Run () {//TODO auto-generated method stub while (true) {synchronized (R) {//This place must
					Must add synchronized block if (inputflag) {r.name = "Mike";
					R.sex = "Man";
				Inputflag = false;
					else {r.name = "Lili";
					R.sex = "female";
				Inputflag = true;
	Class Output implements runnable{Resource R;
	Public Output (Resource r) {THIS.R = R; @Override public void Run () {//TODO auto-generated method stub while (true) {synchronized (R) {//This place lock object one
			To be consistent with the lock object of the above synchronized block, the inconsistency does not satisfy the synchronization condition System.out.println (r.name+ "-----" +r.sex); }}} public class Threadsynchronized {public static void MAin (string[] args) {//TODO auto-generated method stub Resource r = New Resource ();
		Input in = new input (r);
		
		Output out = new output (r);
		thread T1 = new thread (in);
		
		Thread t2 = new Thread (out);
		T1.start ();
	T2.start (); }

}



But the problem came up, all the same structure, the installation expected to be, a "Mike-----man" then a "lily------female." But why is this happening?
This is because the input thread after the CPU, multiple assignments, until the output thread to get the CPU will output a lot of the same data
Solution: Join wait wakeup mechanism

/* Communication between Threads:--------Waiting for Wake mechanism topic Description: First, there is a resource pool (Resource), input thread (input) continuously to the resource pool to add content, output thread (outputs) continuously output content and two threads need to sync
	* */class resource{String name;
	String sex;  Boolean flag = false;
	The token is initially false} class Input implements runnable{Boolean inputflag=false;
	Resource R;
	Input (Resource r) {THIS.R = R; @Override public void Run () {//TODO auto-generated a stub while (true) {if (R.flag)//If the mark bit is false to allow the thread to enter the back The synchronized block of the face, and if true, let the thread wait for try{r.wait ();}
			catch (Exception e) {};
					Synchronized (r) {//This place must be synchronized with block if (inputflag) {r.name = "Mike";
					R.sex = "Man";
				Inputflag = false;
					else {r.name = "Lili";
					R.sex = "female";
				Inputflag = true;
				} R.flag = true; Wakes up a single thread waiting on this object monitor.  If all threads wait on this object, they will choose to wake one of the Threads r.notify ();
	That is, the wake-up output Thread}}} class output implements runnable{Resource R;
	Public Output (Resource r) {THIS.R = R; @Override public void Run () {//TODO auto-generated methodStub while (true) {synchronized (R) {//This place lock object must be consistent with the lock object of the synchronized block above, inconsistent with the synchronization condition if (!r.flag) try{r.wait ();}
				catch (Exception e) {};
				System.out.println (r.name+ "-----" +r.sex);
				R.flag = false;
			R.notify (); }}} public class Threadsynchronized {public static void main (string[] args) {//TODO auto-generated method
		Stub Resource r = New Resource ();
		Input in = new input (r);
		
		Output out = new output (r);
		thread T1 = new thread (in);
		
		Thread t2 = new Thread (out);
		T1.start ();
	T2.start (); }

}


Finally, I can see the results I want.




























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.