Share on Google+Share on Google+

Java Thread IsInterrupt

Advertisement
In this section we are going to describe isInterrupt() method with example in java thread.

Java Thread IsInterrupt

In this section we are going to describe isInterrupt() method with example in java thread.

Thread IsInterrupt :

If you want to check that your thread is interrupted or not, Thread class provide you method isInterrupted(). This method only check the interrupted status of the thread without affecting the running method.

public boolean isInterrupted() : this method return Boolean value by checking that thread is interrupted or not. The interrupted status of the thread does not affected by this method.

Example :  In this example we are checking that our thread is interrupted or not by calling Thread.isInterrupted() method.

public class ThreadIsInterrupt implements Runnable {

	Thread thread;

	public ThreadIsInterrupt() {
		thread = new Thread(this);

	}

	/* Implementing Runnable.run() */
	public void run() {
		try {
			System.out.println("isInterrupted() - " + thread.isInterrupted());
			thread.sleep(500);

			/* Thread interrupted */
			System.out.println("Calling interrupt()method..");
			thread.interrupt();

		} catch (InterruptedException e) {
			System.out.println(e);
		}
		System.out.println("isInterrupted() - " + thread.isInterrupted());

	}

	public static void main(String args[]) throws Exception {
		ThreadIsInterrupt th = new ThreadIsInterrupt();
		th.thread.start();

	}
}

Output :

isInterrupted() - false
Calling interrupt()method..
isInterrupted() - true

Advertisements

Posted on: October 22, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.