Thread waiting and wake-up cases

Define resource classes:

/** define a resource class with two member variables * name, sex * and two threads to operate on the variables in the resource: one assigns a value to name and age; 2 outputs of variables for name and age * / public class resource {public string name; public string sex; public boolean flag = false;

}

Inputthread class implements runnable:

/** the input thread assigns a value to the member variable in the resource object resource * one assignment: Zhang San, male; Next assignment: Li Si, female * / public class inputthread implements runnable {private resource R; public inputthread (resource R) {this. R = R;} Public void run() {int i = 0; while (true) {synchronized (R) {/ / if the flag is true, wait for if (r.flag) {try {r.wait();} Catch (exception Ex) {}} if (I% 2 = = 0) {r.name = "Zhang San"; r.sex = "male";} Else {r.name = "Lisi"; r.sex = "female";}// Wake up the other thread and change the flag to true r.flag = true; r.notify(); } i++; } }

}

The outputthread class implements runnable:

/** output thread: for the member variable in the resource object resource, output the value * / public class outputthread implements runnable {private resource R; public outputthread (resource R) {this. R = R;} Public void run() {while (true) {synchronized (R) {/ / judge whether the flag is false and wait for if (! R.flag) {try {r.wait();} catch (Exception ex) {} } System. out. println(r.name+"..."+ r.sex); // Change the flag to false and wake up the other thread r.flag = false; r.notify(); } } }

}

Test class:

/** start the input thread and output thread to realize the assignment and printing value * / public class threaddemo {public static void main (string [] args) {resource resource = new resource(); inputthread in = new inputthread (resource); outputthread out = new outputthread (resource); thread tin = new thread (in); thread tout = new thread (out); tin. Start(); tout. Start();}}

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>