当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java ThreadGroup destroy()用法及代码示例


ThreadGroup类destroy()方法

  • destroy() 方法在 java.lang 包中可用。
  • destroy() 方法用于销毁这个线程组,当我们销毁这个线程组时,它的子线程组将同时被销毁。
  • destroy() 方法是一个非静态方法,它只能通过类对象访问,如果我们尝试使用类名访问方法,那么我们将得到一个错误。
  • destroy() 方法可能会在销毁该线程组时抛出异常。
    • SecurityException – 当不允许当前线程更新此线程组时,可能会抛出此异常。
      • IllegalThreadStateException – 此异常可能在两种情况下抛出
        • 当这个线程组已经被销毁时。
        • 当此线程组不为空时。

用法:

    public final void destroy();

参数:

  • 它不接受任何参数。

返回值:

这个方法的返回类型是void,它什么都不返回。

例:

// Java program to demonstrate the example 
// of void destroy() method of ThreadGroup 

public class Destroy implements Runnable {
    public static void main(String[] args) {
        Destroy des = new Destroy();
        des.destroyed();
    }

    public void destroyed() {
        try {
            // Create two thread group and the named are base
            // and derived

            ThreadGroup base = new ThreadGroup("Base ThreadGroup");
            ThreadGroup derived = new ThreadGroup(base, "Derived ThreadGroup");

            // create two threads
            Thread th1 = new Thread(base, this);
            Thread th2 = new Thread(derived, this);

            //By using getName() method is to retrieve the
            // name of the thread th1
            System.out.println(th1.getName() + " " + "begins.....");

            // By using start() method is to start its execution 
            // of thread th1
            th1.start();

            //By using getName() method is to retrieve the
            // name of the thread th2
            System.out.println(th2.getName() + " " + "begins.....");


            // By using start() method is to start its execution 
            // of thread th2
            th2.start();

            System.out.println();

            // By using join() method is to wait the current
            // thread till complete execution of another
            // thread

            th1.join();
            th2.join();

            // By using destroy() method is to
            // destroy the thread group named derived
            derived.destroy();
            boolean b1 = derived.isDestroyed();
            System.out.println(derived.getName() + " " + "destroyed" + " " + b1);

            boolean b2 = base.isDestroyed();
            System.out.println(base.getName() + " " + "destroyed" + " " + b2);

        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    // Override run()
    public void run() {
        for (int k = 0; k < 100; ++k)
            ++k;
        System.out.println(Thread.currentThread().getName() + " " + "ends.....");
    }
}

输出

Thread-0 begins.....
Thread-0 ends.....
Thread-1 begins.....

Thread-1 ends.....
Derived ThreadGroup destroyed true
Base ThreadGroup destroyed false


相关用法


注:本文由纯净天空筛选整理自Preeti Jain大神的英文原创作品 Java ThreadGroup destroy() method with example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。