Java并发编程与技术内幕:ThreadGroup线程组应用

Posted 奇异宝

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java并发编程与技术内幕:ThreadGroup线程组应用相关的知识,希望对你有一定的参考价值。


package com.xinboedu.www.test;
 
/**
 * 功能概要:
 * 
 * @author linbingwen
 * @since 2016年6月11日
 */
public class ThreadGroupDemo {
 
    public static void main(String[] args) {
        ThreadGroup threadGroup1 =
        // 这是匿名类写法
        new ThreadGroup("group1") {
            // 继承ThreadGroup并重新定义以下方法
            // 在线程成员抛出unchecked exception
            // 会执行此方法
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println(t.getName() + ": " + e.getMessage());
            }
        };
        // 这是匿名类写法
        Thread thread1 =
        // 这个线程是threadGroup1的一员
        new Thread(threadGroup1, new Runnable() {
            public void run() {
                // 抛出unchecked异常
                throw new RuntimeException("测试异常");
            }
        });
 
        thread1.start();
    }
 
}

 

package com.xinboedu.www.test;
 
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;
 
class Result {
    
    private String name;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
    
}
 
public class SearchTask implements Runnable {
 
    public SearchTask(Result result) {
        this.result = result;
    }
 
    private Result result;
 
    @Override
    public 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
", 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.println("value="+value);
        System.out.printf("Thread %s: %d
", Thread.currentThread().getName(),
                value);
        TimeUnit.SECONDS.sleep(value);
    }
 
    public static void main(String[] args) {
        System.out.println("main thread start:");
        
        //创建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
", threadGroup.activeCount());
        System.out.printf("Information about the Thread Group
");
        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
", threads[i].getName(),
                    threads[i].getState());
        }
        
        waitFinish(threadGroup);
        //将group里面的所有线程都给interpet
        threadGroup.interrupt();
        
        System.out.println("main thread end:");
    }
 
    private static void waitFinish(ThreadGroup threadGroup) {
        while (threadGroup.activeCount() > 0) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
 
}

转自:https://blog.csdn.net/Evankaka/article/details/51627380

package com.xinboedu.www.test; import java.util.Date;import java.util.Random;import java.util.concurrent.TimeUnit; class Result {private String name; public String getName() {return name;} public void setName(String name) {this.name = name;}} 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 ", 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.println("value="+value);System.out.printf("Thread %s: %d ", Thread.currentThread().getName(),value);TimeUnit.SECONDS.sleep(value);} public static void main(String[] args) {System.out.println("main thread start:");//创建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 ", threadGroup.activeCount());System.out.printf("Information about the Thread Group ");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 ", threads[i].getName(),threads[i].getState());}waitFinish(threadGroup);//将group里面的所有线程都给interpetthreadGroup.interrupt();System.out.println("main thread end:");} private static void waitFinish(ThreadGroup threadGroup) {while (threadGroup.activeCount() > 0) {try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}}} }

以上是关于Java并发编程与技术内幕:ThreadGroup线程组应用的主要内容,如果未能解决你的问题,请参考以下文章

Java并发编程与技术内幕:ArrayBlockingQueueLinkedBlockingQueue及SynchronousQueue源码解析

Java并发编程与技术内幕:线程池深入理解

并发编程与技术内幕:线程池深入理解

Java 多线程进阶-并发编程 线程组ThreadGroup

Java并发系列01Thread及ThreadGroup杂谈

Java多线程学习