Java Data Type Tutorial - Java ThreadGroup.interrupt()








Syntax

ThreadGroup.interrupt() has the following syntax.

public final void interrupt()

Example

In the following code shows how to use ThreadGroup.interrupt() method.

//w w  w .  ja  v  a 2 s. c o  m
class MyThread extends Thread {
   MyThread(ThreadGroup group, String name) {
      super(group, name);
   }

   public void run() {
      System.out.println(Thread.currentThread().getName() + " starting.");
      try {
        Thread.sleep(5000);
      }
      catch(Exception e) {
         System.out.print(Thread.currentThread().getName());
         System.out.println(" interrupted.");
      }
      System.out.println(Thread.currentThread().getName() + " exiting.");
   }
}

public class Main {

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

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

     MyThread t1 = new MyThread(group, "Thread1");
     MyThread t2 = new MyThread(group, "Thread2");
   
     t1.start();
     t2.start();
   
     Thread.sleep(1000);

     System.out.println(group.activeCount() + " threads in thread group...");

     Thread th[] = new Thread[group.activeCount()];
     group.enumerate(th);
     for(Thread t : th){
        System.out.println(t.getName());
     }
     Thread.sleep(1000);
    
     System.out.println(group.activeCount() + " threads in thread group...");

     group.interrupt();
  }
}

The code above generates the following result.