How to interrupt a thread?

  1. A thread can be interrupted by calling interrupt() method on the Thread
  2. A thread can be interrupted while running, sleeping and waiting by calling interrupt() on the thread instance.
In this example, from our main() method, we created 3 threads where 1 of them is sleeping, 1 is waiting and the other one is running and called the interrupt() method on all 3 threads to interrupt them. 
public class ThreadInterruptionExample {

    public static void main(String[] args) {
        Thread sleepingThread = new Thread(new SleepTask(), "SLEEPING-THREAD");
        sleepingThread.start();
        sleepingThread.interrupt();

        Object lock = new Object();
        Thread waitingThread = new Thread(new WaitTask(lock), "WAITING-THREAD");
        waitingThread.start();
        waitingThread.interrupt();

        Thread runningThread = new Thread(new RunningTask(), "RUNNING-THREAD");
        runningThread.start();
        runningThread.interrupt();

    }
}

class RunningTask implements Runnable {
    @Override
    public void run() {
        while (true) {
            if (Thread.interrupted()) {
                System.out.println(Thread.currentThread().getName()+": Running thread interruption");
                break;
            }
        }
    }
}

class WaitTask implements Runnable {
    Object lock;

    public WaitTask(Object lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        try {
            synchronized (lock) {
              lock.wait(1000);
}
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName()+ ": "+e);
        }
        
    }
}

class SleepTask implements Runnable {

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ie) {
            System.out.println(Thread.currentThread().getName()+ ": "+ie);
        }
    }

}

Output:
SLEEPING-THREAD: java.lang.InterruptedException: sleep interrupted
WAITING-THREAD: java.lang.InterruptedException
RUNNING-THREAD: Running thread interruption

Comments

Popular posts from this blog

Distributed database design using CAP theorem

SQL Analytical Functions - Partition by (to split resultset into groups)

Easy approach to work with files in Java - Java NIO(New input output)