A communication problem between threads.
Note The prerequisites for synchronization:
1, with two or more threads of two
2, with the same lock
Wait ()
Notify ()
Notifyall ()
All of these methods are defined in the object class.
are used in synchronization because you want to operate on the thread that holds the monitor (locking).
So to use in synchronization, because only synchronization will have a lock.
Why are the methods of these operations threads defined in the object class?
Because these methods must be used to identify only the locks they operate on when the thread is in the process of synchronizing the threads,
Only the same locked waiting thread can be awakened by the same lock notify.
It is not possible to wake a thread with a different lock.
This means that the thread waits and wakes must be the same lock.
A lock can be any object, so the method that can be called by any object is defined in the object class.
*/
This is a code that has been optimized. Class Res{private string Name;private string Sex;boolean flag=false;public synchronized void set (string name,string sex) { if (flag) try{this.wait ();} catch (Exception e) {}this.name=name;this.sex=sex;flag=true;this.notify ();} Public synchronized void out () {if (!flag) try{this.wait ();} catch (Exception e) {}system.out.println (name+ ".... +sex); flag=false;this.notify ();}} Class input implements Runnable{private res R;object obj=new Object (); input (Res R) {this.r=r;} public void Run () {int X=0;while (true) {if (x==0) r.set ("Jhon", "Man"), Elser.set ("Li ...", "Women ..."); x= (x+1)%2;}} Class Output implements Runnable{private res R;output (res r) {this.r=r;} public void Run () {while (true) {R.out ()}}} Class Inputoutputdemo1{public static void Main (string[] args) {res r=new res (); New Thread (New Input (R)). Start (); New Threa D (New Output (R)). Start ();/*input in=new Input (r); output Out=new output (r); Thread T1=new thread (in); Thread T2=new thread (out); T1.start (); T2.start (); */system.out.println ("Hello world!");}}
Java Thread Cheng