This is a multi-thread!

xiaoxiao2021-03-06  56

Class testthread {public static void main (string [] args) {data dd = new data (); t1 t1 = new T1 (DD); T2 T2 = New T2 (DD); t1.start (); t2.start ( }};

Class Data {Char C; Boolean Flag;

Class T1 Extends Thread {data D; public T1 (Data D) {this.d = D; // The front of this is omitted with this}

Public void Run () {for (int i = 0; i <20; i ) {synchronized (d) {while (D.FLAG) {Try {d.wait ();} catch (eRror) {}} DC = (char) (Math.random () * 26); D.FLAG = true; system.out.println ("Generating: DC); D.Notify (); / / Use D.NotifyAll () here; you can wake up all threads} try {thread.sleep ((int) (});}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}

Class T2 Extends Thread {Data D; Public T2 (Data D) {this.d = D;

Public void Run () {for (INT i = 0; i <20; i ) {SYNCHRONIZED (D) {while (! d.flag) {Try {d.wait ();} catch (exception error) {}}} System.out.println ("Generation:" DC); D.Flag = false; D.Notify (); // Use d.notifyall (); you can wake up all threads} try {thread.sleep (int) (Math.random () * 1000);}}}}}}}}}}}}}};

转载请注明原文地址:https://www.9cbs.com/read-82970.html

New Post(0)