位置:首頁 > Java技術 > java.lang > java.lang.ThreadGroup.interrupt()方法實例

java.lang.ThreadGroup.interrupt()方法實例

java.lang.ThreadGroup.interrupt() 方法中斷該線程組中的所有線程。

聲明

以下是java.lang.ThreadGroup.interrupt()方法的聲明

public final void interrupt()

參數

  • NA

返回值

此方法不返回任何值。

異常

  • SecurityException -- 如果當前線程不允許訪問該線程組或任何的線程的線程組中。

例子

下麵的例子顯示java.lang.ThreadGroup.interrupt()方法的使用。

package com.yiibai;

import java.lang.*;

class newThread extends Thread {
   boolean stop;

   newThread(ThreadGroup group, String name) {
      super(group, name);
      stop = false;
   }

   public void run() {
      System.out.println(Thread.currentThread().getName() + " starting.");
      try {
         for(int i = 1; i < 1000; i++) {
            Thread.sleep(500);
            synchronized(this) {
               if(stop)
                  break;
            }   
         }
      }
      catch(Exception e) {
         System.out.print(Thread.currentThread().getName());
         System.out.println(" interrupted.");
      }
      System.out.println(Thread.currentThread().getName() + " exiting.");
   }

   synchronized void stopFunc() {
      stop = true;
   }
}

public class ThreadGroupDemo {

   public static void main(String args[]) throws Exception {

     ThreadGroup group = new ThreadGroup("new Group");

     newThread t1 = new newThread(group, "Thread1");
     newThread t2 = new newThread(group, "Thread2");
   
     // this will call run() method
     t1.start();
     t2.start();
   
     Thread.sleep(1000);

     // it shows current active threads in Thread Group
     System.out.println(group.activeCount() + " threads in thread group...");

     // returns the number of thread groups
     Thread th[] = new Thread[group.activeCount()];
     group.enumerate(th);
     for(Thread t : th)
        System.out.println(t.getName());

     t1.stopFunc();
     Thread.sleep(1000);
    
     System.out.println(group.activeCount() + " threads in thread group...");
     // thread group interrupted
     group.interrupt();
  }
}

讓我們來編譯和運行上麵的程序,這將產生以下結果:

Thread1 starting.
Thread2 starting.
2 threads in thread group...
Thread1
Thread2
Thread1 exiting.
1 threads in thread group...
Thread2 interrupted.
Thread2 exiting.