Interrupting a thread.
This tutorial demonstrate how a thread is interrupted through code.
This tutorial demonstrate how a thread is interrupted through code.
Description:
The interrupt() method exists in the java.lang.Thread class. This method is
used to interrupt the current thread. If current thread is blocked by wait(),
join() or sleep() methods then its interrupt status will be cleared and it will
receive and InterrrupedException. Interrupting a thread that is not alive have
no effect.
Code:
class MyThread1 implements Runnable {
public void run() {
try {
Thread.sleep(40000);
} catch (Exception exc) {
System.out.println(Thread.currentThread().getName()
+ " is interrupted.");
}
System.out.println(Thread.currentThread().getName() + " is exiting.");
}
}
public class ThreadInterrupt1 {
public static void main(String args[]) throws Exception {
Thread th1 = new Thread(new MyThread1(), "First Thread");
Thread th2 = new Thread(new MyThread1(), "Second Thread");
th1.start();
Thread.sleep(200);
th1.interrupt();
th2.start();
Thread.sleep(500);
th2.interrupt();
}
}
|
Output:
Download this code