public class test{//test public static void main (string[] args) throws Exception{object obj = new Object ()//Start two threads Thread1 T1 = new Thread1 (obj); Thread2 t2 = new Thread2 (obj); T1.start (); T2.start ();}} A thread prints 1-52class Thread1 extends Thread{private object obj;public Thread1 (Object obj) {this.obj = obj;} public void Run () {synchronized (obj) {//print 1-52for (int i = 1; i <; i++) {System.out.print (i + ""); if (i% 2 = = 0) {// Do not forget to wake up other threads Obj.notifyall (); try{obj.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}}}}} Another thread prints the letter A-zclass Thread2 extends Thread{private object obj;public Thread2 (Object obj) {this.obj = obj;} public void Run () {synchronized (obj) {//print a-zfor (int i = 0; i <; i++) {System.out.print (char) (' A ' + i) + "");//No Can forget to wake up other threads Obj.notifyall (); try{//the last one, don't wait. if (i! =) {obj.wait ();}} catch (Interruptedexception e) {e.printstacktrace ();}}}}
Threads alternately perform tasks in an orderly manner