

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to interrupt a running thread in Java?
A thread can send an interrupt by invoking interrupt on the Thread object for the thread to be interrupted. This means interruption of a thread is caused by any other thread calling the interrupt() method.
The Thread class provides three interrupt methods
- void interrupt() - Interrupts the thread.
- static boolean interrupted() - Tests whether the current thread has been interrupted.
- boolean isInterrupted() - Tests whether the thread has been interrupted.
Example
public class ThreadInterruptTest { public static void main(String[] args) { System.out.println("Thread main started"); final Task task = new Task(); final Thread thread = new Thread(task); thread.start(); thread.interrupt(); // calling interrupt() method System.out.println("Main Thread finished"); } } class Task implements Runnable { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println("[" + Thread.currentThread().getName() + "] Message " + i); if(Thread.interrupted()) { System.out.println("This thread was interruped by someone calling this Thread.interrupt()"); System.out.println("Cancelling task running in thread " + Thread.currentThread().getName()); System.out.println("After Thread.interrupted() call, JVM reset the interrupted value to: " + Thread.interrupted()); break; } } } }
Output
Thread main started Main Thread finished [Thread-0] Message 0 This thread was interruped by someone calling this Thread.interrupt() Cancelling task running in thread Thread-0 After Thread.interrupted() call, JVM reset the interrupted value to: false
- Related Questions & Answers
- How a thread can interrupt another thread in Java?
- How to create a thread in Java
- How to make a class thread-safe in Java?
- How to make a collection thread safe in java?
- Naming a thread in Java
- How to create a thread in JShell in Java 9?
- How can we stop a thread in Java?
- Running Java in Node.js
- User Thread vs Daemon Thread in Java?
- How to create a thread using lambda expressions in Java?
- How to create a thread using method reference in Java?
- How to get the thread ID from a thread in C#?
- How can we implement a timer thread in Java?
- How to create a thread by using anonymous class in Java?
- Daemon thread in Java
Advertisements