PackageCom.my.lianxi;Importjava.util.ArrayList;Importjava.util.List; Public classThreadTest { Public Static voidMain (string[] args)throwsinterruptedexception {NewMonitor (). Start (); NewMyThread (). Launch (); } } classMyThreadextendsThread {//be scramble for resources Public StaticInteger i = 0; //Thread Container Public Staticlist<mythread> list =NewArraylist<mythread>(); //Start 50 Threads Public voidlaunch () { for(inti = 0; I < 50; i++) {MyThread Temthread=NewMyThread (); List.add (Temthread); Temthread.start (); }} @Override Public voidrun () {Try { //Increase Scramble StrengthThread.Sleep (2); } Catch(interruptedexception e) {e.printstacktrace (); } synchronized(mythread.i) {//the main taskmythread.i++; } } } classMonitorextendsThread { Public intn = 0; @Override Public voidrun () { while(true) { Try { //Heartbeat 1 secondsSleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } //determines whether the thread ends BooleanIsover =true; for(MyThread thread:MyThread.list) {//if there's one alive, it's not over. if(Thread.isalive ()) {Isover=false; } } //Output Formatting if(n% = = 0 && n! = 0) {System.out.println (); } //result Output if(isover) {System.out.print (n+ + + "-" + mythread.i + ";"); synchronized(mythread.i) {mythread.i= 0; } mythread.list=NewArraylist<mythread>(); NewMyThread (). Launch (); } } } }
Java Implementation Multithreading