Java ThreadGroup interrupt() Method

The ThreadGroup.interrupt() method in Java is used to interrupt all threads in the thread group. This guide will cover the method's usage, explain how it works, and provide examples to demonstrate its functionality.

Table of Contents

  1. Introduction
  2. interrupt() Method Syntax
  3. Understanding interrupt()
  4. Examples
    • Basic Usage
    • Using interrupt() with Subgroups
  5. Real-World Use Case
  6. Conclusion

Introduction

The ThreadGroup.interrupt() method is used to interrupt all threads in the thread group and its subgroups. This can be useful for stopping a group of threads simultaneously.

interrupt() Method Syntax

The syntax for the interrupt() method is as follows:

public void interrupt()

Parameters:

  • This method does not take any parameters.

Returns:

  • This method does not return any value.

Understanding interrupt()

The interrupt() method iterates over all active threads in the thread group and its subgroups, calling interrupt() on each one. This method does not interrupt threads that are not in the active state.

Examples

Basic Usage

To demonstrate the basic usage of interrupt(), we will create a simple example where multiple threads are added to a thread group, and the thread group is interrupted.

Example

public class ThreadGroupInterruptExample {
    public static void main(String[] args) {
        ThreadGroup group = new ThreadGroup("ExampleGroup");

        Runnable task = () -> {
            try {
                while (!Thread.currentThread().isInterrupted()) {
                    System.out.println(Thread.currentThread().getName() + " is running");
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getName() + " was interrupted");
            }
        };

        Thread thread1 = new Thread(group, task, "Thread-1");
        Thread thread2 = new Thread(group, task, "Thread-2");
        Thread thread3 = new Thread(group, task, "Thread-3");

        thread1.start();
        thread2.start();
        thread3.start();

        // Allow threads to run for a short time
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Interrupt all threads in the group
        group.interrupt();
    }
}

Output:

Thread-1 is running
Thread-2 is running
Thread-3 is running
Thread-1 is running
Thread-2 is running
Thread-3 is running
Thread-1 was interrupted
Thread-2 was interrupted
Thread-3 was interrupted

Using interrupt() with Subgroups

You can use the interrupt() method to interrupt threads in nested groups as well.

Example

public class ThreadGroupSubgroupsInterruptExample {
    public static void main(String[] args) {
        ThreadGroup parentGroup = new ThreadGroup("ParentGroup");
        ThreadGroup childGroup = new ThreadGroup(parentGroup, "ChildGroup");

        Runnable task = () -> {
            try {
                while (!Thread.currentThread().isInterrupted()) {
                    System.out.println(Thread.currentThread().getName() + " is running");
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getName() + " was interrupted");
            }
        };

        Thread thread1 = new Thread(parentGroup, task, "Thread-1");
        Thread thread2 = new Thread(childGroup, task, "Thread-2");
        Thread thread3 = new Thread(childGroup, task, "Thread-3");

        thread1.start();
        thread2.start();
        thread3.start();

        // Allow threads to run for a short time
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Interrupt all threads in the parent group (including subgroups)
        parentGroup.interrupt();
    }
}

Output:

Thread-1 is running
Thread-2 is running
Thread-3 is running
Thread-1 is running
Thread-2 is running
Thread-3 is running
Thread-1 was interrupted
Thread-2 was interrupted
Thread-3 was interrupted

Real-World Use Case

Gracefully Stopping a Group of Worker Threads

In a multi-threaded application, you might have a group of worker threads performing tasks. Using ThreadGroup.interrupt(), you can gracefully stop all the worker threads when a certain condition is met or when the application is shutting down.

Example

public class WorkerThreadsExample {
    public static void main(String[] args) {
        ThreadGroup workerGroup = new ThreadGroup("WorkerGroup");

        Runnable task = () -> {
            try {
                while (!Thread.currentThread().isInterrupted()) {
                    System.out.println(Thread.currentThread().getName() + " is processing");
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getName() + " was interrupted");
            }
        };

        for (int i = 0; i < 5; i++) {
            new Thread(workerGroup, task, "Worker-" + i).start();
        }

        // Allow workers to process for a short time
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Stop all worker threads
        System.out.println("Interrupting all worker threads...");
        workerGroup.interrupt();
    }
}

Output:

Worker-0 is processing
Worker-1 is processing
Worker-2 is processing
Worker-3 is processing
Worker-4 is processing
Worker-0 is processing
Worker-1 is processing
Worker-2 is processing
Worker-3 is processing
Worker-4 is processing
Worker-0 is processing
Worker-1 is processing
Worker-2 is processing
Worker-3 is processing
Worker-4 is processing
Interrupting all worker threads...
Worker-0 was interrupted
Worker-1 was interrupted
Worker-2 was interrupted
Worker-3 was interrupted
Worker-4 was interrupted

Conclusion

The ThreadGroup.interrupt() method in Java provides a way to interrupt all threads in a thread group and its subgroups. By using this method, you can manage and control the execution of threads efficiently, ensuring that groups of threads can be stopped gracefully when needed. Whether you are working with simple thread groups or complex thread hierarchies, the ThreadGroup.interrupt() method offers a reliable tool for managing thread execution.

Comments