线程的分组

  Java API提供了一个有趣的功能,它能够把线程分组。这允许我们把一个组的线程当成一个单一的单元,对组内线程对象进行访问并操作他们。例如,对于一些执行同样任务的线程,你想控制它们,不管多少线程在运行,只需要一个单一的调用,所有这些线程的运行都会被中断。

  Java提供ThreadGroup类表示一组线程。线程组可以包含线程对象,也可以包含其他的线程组对象,它是一个树形结构。

  下面我们学习使用ThreadGroup对象类开发一个简单的范例:创建10个线程并让它们休眠一个随机的时间(例如模拟一个查询),当其中一个线程查找成功的时候,我们将中断其它9个线程。

1. 创建一个名为Result的类

public class Result {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
}

2. 创建一个名为SearchTask的类

import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;


public class SearchTask implements Runnable {
    private Result result;
    public SearchTask(Result result){
        this.result = result;
    }
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.printf("Thread %s: Start\n", name);
        try {
            doTask();
            result.setName(name);
        } catch (InterruptedException e) {
            System.out.printf("Thread %s: Interrupted\n", name);
            return;
        }
        System.out.printf("Thread %s: End\n", name);
    }

    private void doTask() throws InterruptedException{
        Random r = new Random((new Date()).getTime());
        int value = (int) (r.nextDouble()*100);
        System.out.printf("Thread %s: %d\n", Thread.currentThread().getName(), value);
        TimeUnit.SECONDS.sleep(value);
    }
    
}

3. 创建主类Main

import java.util.concurrent.TimeUnit;


public class Main {

    public static void main(String[] args) {
        //创建线程组
        ThreadGroup threadGroup = new ThreadGroup("Searcher");
        Result result = new Result();
        SearchTask st = new SearchTask(result);
        try {
            for(int i=0;i<10;i++){
                Thread t = new Thread(threadGroup, st);
                t.start();
                TimeUnit.SECONDS.sleep(1);
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.printf("Number of Threads: %d\n", threadGroup.activeCount());
        System.out.printf("Information about the Thread Group\n");
        threadGroup.list(); //打印线程组的信息
        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());
        }
        //等到线程组的第一个线程运行结束
        try {
            while(threadGroup.activeCount()>9){
                TimeUnit.SECONDS.sleep(1);
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //中断线程组中的其它线程
        threadGroup.interrupt();
    }
}

4. 程序运行结果如下

Thread Thread-0: Start
Thread Thread-0: 75
Thread Thread-1: Start
Thread Thread-1: 11
Thread Thread-2: Start
Thread Thread-2: 99
Thread Thread-3: Start
Thread Thread-3: 27
Thread Thread-4: Start
Thread Thread-4: 18
Thread Thread-5: Start
Thread Thread-5: 46
Thread Thread-6: Start
Thread Thread-6: 37
Thread Thread-7: Start
Thread Thread-7: 18
Thread Thread-8: Start
Thread Thread-8: 6
Thread Thread-9: Start
Thread Thread-9: 34
Number of Threads: 10
Information about the Thread Group
java.lang.ThreadGroup[name=Searcher,maxpri=10]
    Thread[Thread-0,5,Searcher]
    Thread[Thread-1,5,Searcher]
    Thread[Thread-2,5,Searcher]
    Thread[Thread-3,5,Searcher]
    Thread[Thread-4,5,Searcher]
    Thread[Thread-5,5,Searcher]
    Thread[Thread-6,5,Searcher]
    Thread[Thread-7,5,Searcher]
    Thread[Thread-8,5,Searcher]
    Thread[Thread-9,5,Searcher]
Thread Thread-0: TIMED_WAITING
Thread Thread-1: TIMED_WAITING
Thread Thread-2: TIMED_WAITING
Thread Thread-3: TIMED_WAITING
Thread Thread-4: TIMED_WAITING
Thread Thread-5: TIMED_WAITING
Thread Thread-6: TIMED_WAITING
Thread Thread-7: TIMED_WAITING
Thread Thread-8: TIMED_WAITING
Thread Thread-9: TIMED_WAITING
Thread Thread-1: End
Thread Thread-3: Interrupted
Thread Thread-2: Interrupted
Thread Thread-0: Interrupted
Thread Thread-4: Interrupted
Thread Thread-6: Interrupted
Thread Thread-5: Interrupted
Thread Thread-8: Interrupted
Thread Thread-7: Interrupted
Thread Thread-9: Interrupted

 

posted @ 2015-10-24 12:08  ~风轻云淡~  阅读(678)  评论(0编辑  收藏  举报