multi-thread(二)ThreadGroup

来源:互联网 发布:学数控编程用什么软件 编辑:程序博客网 时间:2024/05/21 10:27

 

1、ThreadGroup,统一管理线程,比如优先级,interrupt等

 

public class MyThreadGroup {    public static void main( String args[] )        throws Exception {        ThreadGroup tg = new ThreadGroup( "My Group" );        MyThread1 thrd1 = new MyThread1( tg, "MyThread #1" );        MyThread1 thrd2 = new MyThread1( tg, "MyThread #2" );        MyThread1 thrd3 = new MyThread1( tg, "MyThread #3" );        thrd1.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() );        thrd1.myStop();        Thread.sleep( 1000 );        System.out.println( tg.activeCount() + " threads in thread group." );        tg.interrupt();    }}class MyThread1 extends Thread {    boolean stopped;    MyThread1( ThreadGroup tg, String name ) {        super( tg, name );        stopped = false;    }    public void run() {        System.out.println( Thread.currentThread() + "is starting." );        try {            for ( int i = 1; i < 1000; i++ ) {                System.out.print( "." );                Thread.sleep( 250 );                synchronized ( this ) {                    if ( stopped )                        break;                }            }        }        catch ( InterruptedException exc ) {            System.out.println( Thread.currentThread() + ": " + exc );        }        System.out.println( Thread.currentThread() + "is end." );    }    synchronized void myStop() {        stopped = true;    }}

 

 

原创粉丝点击