Java ThreadGroup destroy()方法

2019-10-16 22:23:55

ThreadGroup類的destroy()方法用於銷毀執行緒組及其所有子組。 執行緒組必須為空,表示執行緒組中的所有執行緒都已停止。

語法

public void destroy()

返回
它不會返回任何值。

例外

  • IllegalThreadStateException:如果執行緒組不為空或者執行緒組已被銷毀,則丟擲此異常。
  • SecurityException:如果當前執行緒無法修改此執行緒組。

範例

package com.yiibai.threadgroup;

class NewThread extends Thread {
    NewThread(String threadname, ThreadGroup tg) {
        super(tg, threadname);
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException ex) {
                System.out.println(Thread.currentThread().getName() + " interrupted");
            }
        }
        System.out.println(Thread.currentThread().getName() + " completed executing");
    }
}

public class ThreadGroupDestroyExp {
    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
        NewThread t1 = new NewThread("Thread-1", g1);
        t1.start();
        // creating another thread
        NewThread t2 = new NewThread("Thread-2", g1);
        t2.start();

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

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

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

執行上面範例程式碼,得到以下結果:

Thread-2 completed executing
Thread-1 completed executing
Child thread destroyed
Parent thread destroyed