When several threads are created, many threads have similar or consistent work tasks, so that we can use Threadgroup to manage his
, Threadgroup can always get the running state of the thread in him, the information, or a command to shut down all the lines in the group.
process, very simple and practical, below we use an example to illustrate how to use.
Package Com.bird.concursey;import Java.util.date;import Java.util.random;import java.util.concurrent.TimeUnit; public class Searchtask implements Runnable {public searchtask (result result) {This.result = result;} private result result; @Overridepublic void Run () {String name = Thread.CurrentThread (). GetName (); System.out.println ("Thread Start" + name); try {dotask (); Result.setname (name);} catch (Interruptedexception e) {System.out.printf ("Thread%s:interrupted\n", name); return;} System.out.println ("Thread end" + name);} private void Dotask () throws interruptedexception {random random = new Random (new Date ()). GetTime ()); int value = (int) (r Andom.nextdouble () * 100); System.out.printf ("Thread%s:%d\n", Thread.CurrentThread (). GetName (), value); TimeUnit.SECONDS.sleep (value);} public static void Main (string[] args) {//Create 5 threads to be merged into Group for management threadgroup Threadgroup = new Threadgroup ("Searcher"); Result result = new result (); Searchtask searchtask = new Searchtask (result); for (int i = 0; i < 5; i++) {Thread thred = new Thread (Threadgroup, searchtask); Thred.start (); try {TimeUnit.SECONDS.sleep (1);} catch ( Interruptedexception e) {e.printstacktrace ();}} This way you can see all the information in group System.out.printf ("Number of Threads:%d\n", Threadgroup.activecount ()); System.out.printf ("Information about the thread group\n"); Threadgroup.list ();//This allows you to copy the thread information inside the Group thread[] Threads = new Thread[threadgroup.activecount ()];threadgroup.enumerate (threads); for (int i = 0; i < Threadgroup.activecount (); i++) {System.out.printf ("Thread%s:%s\n", Threads[i].getname (), threads[i].getstate ());} Waitfinish (Threadgroup);//Give Interpetthreadgroup.interrupt () all the threads inside the group;} private static void Waitfinish (Threadgroup threadgroup) {while (Threadgroup.activecount () > 9) {try {timeunit.seconds . Sleep (1);} catch (Interruptedexception e) {e.printstacktrace ();}}}}
Java multi-thread---threadgroup management thread