线程并发三:线程组和守护线程

来源:互联网 发布:互联网过滤软件 编辑:程序博客网 时间:2024/05/17 21:40

1.线程组
在一个系统中,如果线程数量过多,而且功能分配明确,就可以将功能相同的线程放在同一个线程组中。线程组的使用非常简单:

public class ThreadGroupTest implements Runnable {    @Override    public void run() {        String groupAndThreadName = Thread.currentThread().getThreadGroup().getName() + ":" + Thread.currentThread().getName();        while (true) {            System.out.println("now process " + groupAndThreadName);            try {                Thread.sleep(3000);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }    }    public static void main(String[] args){        ThreadGroup tg = new ThreadGroup("testGroup");        Thread t1 = new Thread(tg, new ThreadGroupTest(), "test1");        Thread t2 = new Thread(tg, new ThreadGroupTest(), "test2");        t1.start();        t2.start();        System.out.println(tg.activeCount());        tg.list();        tg.stop();    }}

activeCount()可以获取活动线程的总数,但由于线程是动态的,因此这个值只是个估计值,无法确定精确。 list()方法可以打印这个线程组中所有的线程信息。线程组还有一个值得注意的方法 stop(),它会停止线程组中所有的线程,这个看起来是一个很方便的功能,但是它会遇到和Thread.stop()相同的问题,使用是要格外谨慎。

2.守护线程(Daemon)
守护线程是一种特殊的线程,它是系统的守护者,在后台默默的完成一些系统性的服务,比如垃圾回收线程,JIT线程。值得注意的是,当java应用中,只有守护线程时,java虚拟机就会自然退出。

public class DaemonTest {    public static class DaemonT extends Thread {        public void run(){            while (true) {                System.out.println("I am alive!!");                try {                    Thread.sleep(1000);                } catch (InterruptedException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }        public static void main(String[] args) throws InterruptedException{            Thread t1 = new DaemonT();            t1.setDaemon(true);            t1.start();            Thread.sleep(5000);        }    }}

这里要注意的时设置守护线程必选在线程start()之前。否则设置守护线程会出现异常,但是确实作为用户线程运行,永远停不下来。

原创粉丝点击