Home Tutorial Java Core Java Thread Interrupted

 
 

Share on Google+Share on Google+
Java Thread Interrupted
Posted on: October 23, 2012 at 12:00 AM
Advertisement
In this tutorial, you will learn how to interrupt a thread with example in Java.

Java Thread Interrupted

In this tutorial, you will learn how to interrupt a thread with example in Java.

Thread Interrupt :

Java thread facilitate you to interrupt any thread. Interrupting a thread means to stop the running thread without caring of its process and do some another task. You can put another task after interruption or can terminate the thread.
The main motive to interrupt any thread is to abort the current operation then its application requirement whether thread die or do another task.

public void interrupt() : This method interrupts the specified thread. It throws SecurityException if the current thread can't modify.

public static boolean interrupted() : This method checks for the thread interruption. It is of Boolean type,so return true if interrupted otherwise return false.

Example : In this example we are checking whether thread is interrupted  or not.

public class ThreadInterrupt implements Runnable {

	Thread thread;

	public ThreadInterrupt() {
		thread = new Thread(this);
		System.out.println(thread.getName() + " is going to start...");
		thread.start();
		try {
			Thread.sleep(500);
			if (!thread.interrupted()) {
				thread.interrupt();
				System.out.println("Thread interrupted...");
			}
			thread.join();
		} catch (InterruptedException e) {

		}

	}

	public void run() {
		try {
			System.out.println(thread + " is executing.");
			Thread.sleep(500);

		} catch (InterruptedException e) {
			System.out.println(thread.getName() + " was interrupted: "
					+ e.toString());
		}
	}

	public static void main(String args[]) {
		new ThreadInterrupt();

	}
}

Output :

Thread-0 is going to start...
Thread[Thread-0,5,main] is executing.
Thread interrupted...

Advertisement

Related Tags for Java Thread Interrupted:


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: October 23, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com