Recently learned multi-threading, search, full screen problems are similar to the title of the same, so take this as a start, I tried a hand,
Several times the computer CPU ran to 100%, finally still write out, the general idea is:
Declares a variable that marks three threads for which thread to output, each output will be the variable +1, judging by the variable to 3 of the remainder, if 1-a,2-b, 3-c
1 Public classABC {2 3 Private Static intMark = 0;4 5 Private StaticObject obj =NewObject ();6 7 Public Static voidMain (string[] args)throwsException {8ABC abc =NewABC ();9 NewThread (ABC.NewPrintA ()). Start ();Ten NewThread (ABC.NewPRINTB ()). Start (); One NewThread (ABC.NewPRINTC ()). Start (); A } - - classPrintAImplementsrunnable{ the - @Override - Public voidrun () { - for(inti = 0; I < 10; i++){ + synchronized(obj) { - while(Mark%3! = 0){ + Try { A obj.wait (); at}Catch(interruptedexception e) { - e.printstacktrace (); - } - } -System.out.print ("A"); -Mark + +; in Obj.notifyall (); - } to } + } - } the classPrintbImplementsrunnable{ * $ @OverridePanax Notoginseng Public voidrun () { - for(inti = 0; I < 10; i++){ the synchronized(obj) { + while(Mark%3! = 1){ A Try { the obj.wait (); +}Catch(interruptedexception e) { - e.printstacktrace (); $ } $ } -System.out.print ("B"); -Mark + +; the Obj.notifyall (); - }Wuyi } the } - } Wu classPrintcImplementsrunnable{ - About @Override $ Public voidrun () { - for(inti = 0; I < 10; i++){ - synchronized(obj) { - while(Mark%3! = 2){ A Try { + obj.wait (); the}Catch(interruptedexception e) { - e.printstacktrace (); $ } the } theSystem.out.println ("C"); theMark + +; the Obj.notifyall (); - } in } the } the } About}
Java multithreaded open three threads output ABC10 times