Java Thread Interrupted


 

Java Thread Interrupted

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

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...

Ads