Package demo;/** * Sub-thread loops 5 times and the main thread loops 10 times. Alternating in turn. The entire alternating loop 3 times * */public class ThreadTest {public static void main (string[] args) {init ();} static void Init () {final print P = new print ();//encapsulates the action of the Loop new Thread (new Runnable () {@Overridepublic void Run () {for (int i= 0;i<3;i++) {p.subprint (5);//Cycle 5 }}). Start (); New Thread (New Runnable () {@Overridepublic void Run () {for ( int i=0;i<3;i++) {p.mainprint (10);//Cycle 10 }}). Start ();}}
Print:
Package demo;/** * Two methods mutually exclusive (the method inside the complete execution), with the Sflag switch control two methods of switching * */public class Print {Boolean sflag = true; Public synchronized void Subprint (int. num) {while (! Sflag) {//Avoid pseudo-wake try {this.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}} for (int i=1;i<=num;i++) {System.out.println (Thread.CurrentThread (). GetName () + ":" +i);} Sflag = False;this.notifyall ();} Public synchronized void Mainprint (int. num) {while (Sflag) {try {this.wait ();} catch (Interruptedexception e) { E.printstacktrace ();}} for (int i=1;i<=num;i++) {System.out.println (Thread.CurrentThread (). GetName () + ":" +i);} Sflag = True;this.notifyall ();}}
Sub-threading and main thread interchange