Create a thread corresponding to the type, three threads are processed separately.
Call three different threads, cycle through 5 numbers, wake up other dormant threads after printing, and hibernate yourself.
1 PackageThread;2 /**3 * Three threads in turn print 1-75, one thread prints 5 numbers at a time4 * @authorAdministrator5 *6 */7 8 Public classThreaddemo {9 //thread-corresponding type, three threads separate processingTen Static intType = 1; One Static intNumber = 1; A Public Static voidMain (string[] args) { - NewThread ("First thread:") {//Create a thread that is named the first thread - Public voidrun () { the Try { - synchronized(Threaddemo.class) { - while(Number <= 75) { - //when the value of type is 1, it is printed by the first thread + if(Type = = 1) { - for(inti = 0; I < 5; i++) { +System.out.println (Thread.CurrentThread (). GetName () + ":" + number++); A } at //Modifying Type Values -Type = 2; - //waking other threads into hibernation -Threaddemo.class. Notifyall (); - //The current thread has finished executing into hibernation -Threaddemo.class. Wait (); in}Else { -Threaddemo.class. Wait (); to } + } - } the}Catch(interruptedexception e) { * e.printstacktrace (); $ }Panax Notoginseng }; - }.start (); the NewThread ("Second thread:") {//Create two threads, named first thread + Public voidrun () { A Try { the synchronized(Threaddemo.class) { + while(Number <= 75) { - if(Type = = 2) { $ for(inti = 0; I < 5; i++) { $System.out.println (Thread.CurrentThread (). GetName () + ":" + number++); - } -Type = 3; theThreaddemo.class. Notifyall (); -Threaddemo.class. Wait ();Wuyi}Else { theThreaddemo.class. Wait (); - } Wu } - } About}Catch(interruptedexception e) { $ e.printstacktrace (); - } - }; - }.start (); A NewThread ("Third thread:") {//Create three threads, named first thread + Public voidrun () { the Try { - synchronized(Threaddemo.class) { $ while(Number <= 75) { the if(Type = = 3) { the for(inti = 0; I < 5; i++) { theSystem.out.println (Thread.CurrentThread (). GetName () + ":" + number++); the } -Type = 1; inThreaddemo.class. Notifyall (); the if(Number < 76) the ; AboutThreaddemo.class. Wait (); the}Else { theThreaddemo.class. Wait (); the } + } - } the}Catch(interruptedexception e) {Bayi e.printstacktrace (); the } the }; - }.start (); - } the}
Three threads in turn print 1-75, one thread prints 5 numbers at a time