Java Thread destroy()方法

java.lang.Thread.destroy() 方法用于销毁线程组及其所有子组。线程组必须为空,表示该线程组中的所有线程此后都已停止。

1 语法

public void destroy()  

2 参数

3 返回值

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.lang.Thread.destroy()方法的例子
 */
public class Demo extends Thread
{
    Demo(String threadname, ThreadGroup tg)
    {
        super(tg, threadname);
        start();
    }
    public void run()
    {
        for (int i = 0; i < 2; i++)
        {
            try
            {
                Thread.sleep(10);
            }
            catch (InterruptedException ex) {
                System.out.println("Exception encounterted");}
        }
        System.out.println(Thread.currentThread().getName() +
                " finished executing");
    }
    public static void main(String arg[]) throws InterruptedException, SecurityException
    {
        // creating a ThreadGroup
        ThreadGroup g1 = new ThreadGroup("Parent thread");
        // creating a child ThreadGroup for parent ThreadGroup
        ThreadGroup g2 = new ThreadGroup(g1, "child thread");

        // creating a thread
        Demo t1 = new Demo("Thread-1", g1);
        // creating another thread
        Demo t2 = new Demo("Thread-2", g1);

        // block until other thread is finished
        t1.join();
        t2.join();

        // destroying child thread
        g2.destroy();
        System.out.println(g2.getName() + " destroyed");

        // destroying parent thread
        g1.destroy();
        System.out.println(g1.getName() + " destroyed");
    }
}

输出结果为:

Thread-1 finished executing
Thread-2 finished executing
child thread destroyed
Parent thread destroyed

热门文章

优秀文章