[JavaSE] multi-thread communication (wait-wake-up mechanism) and javase Multithreading
When two threads operate on the same resource, for example, the input and output operations on the same object, the two threads compete for the cpu execution right and perform random switching. We want to implement input, output, and sequential execution.
The target object defines a tag field for judgment. The wait () and Y () Methods
Wait () method. The thread is in the waiting state, and the waiting thread is in the thread pool in the memory.
Y () method to wake up threads in the thread pool
Yyall () method to wake up all threads
The above method needs to be written in the synchronization and the identification lock is required.
The methods of these operation threads are defined in the Object, because these methods must be called through the same lock Object.
/*** Resource ** @ author taoshihan **/class People {String name; String sex; Boolean myLock = false ;} /*** input ** @ author taoshihan **/class PeopleJoin implements Runnable {private People resource; public PeopleJoin (People resource) {this. resource = resource ;}@ Override public void run () {// switch boolean flag = true; while (true) {synchronized (resource) {if (resource. myLock) {try {resource. wa It ();} catch (InterruptedException e) {e. printStackTrace () ;}} if (flag) {resource. name = "taoshihan"; resource. sex = "nan";} else {resource. name = "Tao shihan"; resource. sex = "male";} flag =! Flag; resource. myLock = true; resource. Y () ;}}}/*** output ** @ author taoshihan **/class PeopleOut implements Runnable {private People resource; public PeopleOut (People resource) {this. resource = resource;} @ Override public void run () {while (true) {synchronized (resource) {if (! Resource. myLock) {try {resource. wait ();} catch (InterruptedException e) {e. printStackTrace () ;}} System. out. println (resource. name + "=" + resource. sex); resource. myLock = false; resource. notify () ;}}} public class ThreadDemo {/*** @ param args */public static void main (String [] args) {People resource = new People (); peopleJoin input = new PeopleJoin (resource); PeopleOut output = new PeopleOut (resource); Thread t1 = new Thread (input); Thread t2 = new Thread (output); t1.start (); t2.start ();}}