Home Tutorial Java Corejava Interrupting a thread.

 
 

Share on Google+Share on Google+
Interrupting a thread.
Posted on: June 25, 2010 at 12:00 AM
Advertisement
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

Advertisement

Related Tags for Interrupting a thread.:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 25, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com