Java多线程之---ThreadGroup 管理Thread

来源:互联网 发布:unity3d 自动寻路 编辑:程序博客网 时间:2024/05/17 05:16

当创建了好几个线程的时候,很多线程的工作任务是类似或者一致的,这样我们就可以使用ThreadGroup来管理他

们,ThreadGroup可以随时的获取在他里面的线程的运行状态,信息,或者一条命令关闭掉这个group里面的所有线

程,非常的简单实用,下面我们用一个例子来说明一下如何使用。


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) {//创建5个线程,并入group里面进行管理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();}}//通过这种方法可以看group里面的所有信息System.out.printf("Number of Threads: %d\n", threadGroup.activeCount());System.out.printf("Information about the Thread Group\n");threadGroup.list();//这样可以复制group里面的thread信息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);//将group里面的所有线程都给interpetthreadGroup.interrupt();}private static void waitFinish(ThreadGroup threadGroup) {while (threadGroup.activeCount() > 9) {try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}}}}


4 0
原创粉丝点击