How to interrupt a thread?
- A thread can be interrupted by calling interrupt() method on the Thread
- 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
Post a Comment