Java ThreadGroup interrupt()方法

2019-10-16 22:24:01

ThreadGroup類的interrupt()方法用於中斷執行緒組中的所有執行緒。

語法

public final void interrupt()

返回
此方法不返回任何值。

異常

  • SecurityException:如果不允許當前執行緒存取執行緒組或執行緒組中的任何執行緒,則丟擲此異常。

範例

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 ThreadGroupInterruptExp  
{  
    public static void main(String arg[]) throws InterruptedException,  
        SecurityException  
    {  
        // creating the thread group  
        ThreadGroup tg1 = new ThreadGroup("Parent thread");  
        ThreadGroup tg2 = new ThreadGroup(tg1, "child thread");  

        // creating a thread   
        NewThread t1 = new NewThread("Thread-1", tg1);  
        System.out.println(t1.getName() + " starts");  
        t1.start();  

        // interrupting thread group  
        tg1.interrupt();  

        // creating another thread   
        NewThread t2 = new NewThread("Thread-2", tg1);  
        System.out.println(t2.getName() + " starts");  
        t2.start();  
    }  
}

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

Thread-1 starts
Thread-2 starts
Thread-1 interrupted
Thread-1 completed executing
Thread-2 completed executing