Java multithreading --- ThreadGroup management Thread
When several threads are created, many multi-threaded jobs are similar or consistent, so that we can use ThreadGroup to manage them.
ThreadGroup can obtain the running status and information of the threads in the group at any time, or use a command to close all the threads in the group.
It is very simple and practical. Next we will use an example to illustrate how to use it.
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) (random. nextDouble () * 100); System. out. printf ("Thread % s: % d \ n", Thread. currentThread (). getName (), value); TimeUnit. SECONDS. sleep (value);} public static void main (String [] args) {// create five threads and merge them into the group to manage 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 () ;}/// you can use this method to view all information in the group System. out. printf ("Number of Threads: % d \ n", threadGroup. activeCount (); System. out. printf ("Information about the Thread Group \ n"); threadGroup. list (); // copy the thread information in 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); // send all threads in the group to interpetthreadGroup. interrupt ();} private static void waitFinish (ThreadGroup threadGroup) {while (threadGroup. activeCount ()> 9) {try {TimeUnit. SECONDS. sleep (1);} catch (InterruptedException e) {e. printStackTrace ();}}}}