Java——线程组的两种常见用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lhc2207221755/article/details/80835971
/**
 * \* Created: liuhuichao
 * \* Date: 2018/6/4
 * \* Time: 下午4:01
 * \* Description: thread group 常用
 * \
 */
public class ThreadGroupTest {

    /**
     * 复制线程组
     * @throws Exception
     */
    @Test
    public void simpleUseTest() throws Exception{
        ThreadGroup group1=new ThreadGroup("group1");
        Runnable r1=(()->{
            try {
                Thread.sleep(8000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread t1=new Thread(group1,r1,"t1");
        t1.start();
        //复制线程组
        Thread[] threads=new Thread[group1.activeCount()];
        group1.enumerate(threads);
        System.out.println(threads.length);
    }

    /**
     * 线程组统一异常处理
     */
    @Test
    public void threadGroupExceptionSet() throws Exception{
        CountDownLatch seaphere=new CountDownLatch(1);
        ThreadGroup group1=new ThreadGroup("group1"){
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println("线程名称:"+t.getName());
                seaphere.countDown();
            }
        };
        Runnable r1=()->{
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int a=1/0;
            seaphere.countDown();
        };
        Thread t1=new Thread(group1,r1,"t1");
        t1.start();
        seaphere.await();
    }

}

猜你喜欢

转载自blog.csdn.net/lhc2207221755/article/details/80835971
今日推荐