Java多线程(4)线程组


Java并发 API里有个有趣的方法是把线程分组。这个方法允许我们按线程组作为一个单位来处理。例如,你有一些线程做着同样的任务,你想控制他们,无论多少线程还在运行,他们的状态会被一个call 中断。


【类比就是你想控制一批人,利用这些线程来完成一些任务,进行统一的管理和监控】


例子:

public class ThreadGroupTest {

    public static void main(String args[]) throws Exception {
        ThreadGroup tg = new ThreadGroup("My Group");
        MyThread thrd = new MyThread(tg, "MyThread #1");
        MyThread thrd2 = new MyThread(tg, "MyThread #2");
        MyThread thrd3 = new MyThread(tg, "MyThread #3");
        thrd.start();
        thrd2.start();
        thrd3.start();
        Thread.sleep(1000);
        System.out.println(tg.activeCount() + " threads in thread group.");
        Thread thrds[] = new Thread[tg.activeCount()];
        tg.enumerate(thrds);
        for (Thread t : thrds)
            System.out.println(t.getName());
        thrd.myStop();
        Thread.sleep(1000);
        System.out.println(tg.activeCount() + " threads in tg.");
        System.out.println(tg.activeCount());
        tg.interrupt();
    }
}


class MyThread extends Thread {
    boolean stopped;
    MyThread(ThreadGroup tg, String name) {
        super(tg, name);
        stopped = false;
    }
    public void run() {
        System.out.println(Thread.currentThread().getName() + " starting.");
        try {
            for (int i = 1; i < 1000; i++) {
                System.out.print(".");
                Thread.sleep(250);
                synchronized (this) {
                    if (stopped)break;
                }
            }
        } catch (Exception exc) {
            System.out.println(Thread.currentThread().getName() + " interrupted.");
        }
        System.out.println(Thread.currentThread().getName() + " exiting.");
    }
    synchronized void myStop() {
        stopped = true;
    }
}

需要说明的是,一旦某个线程加入了一个线程组是不能进行更改的。线程组提供了中断所有进程,返回活动线程数目等相关的API


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值