Home > Java > javaTutorial > body text

How to interrupt a running thread in Java?

WBOY
Release: 2023-09-18 13:49:02
forward
861 people have browsed it

How to interrupt a running thread in Java?

The thread can interrupt the thread by sending an interrupt signal by calling the interrupt() method of the thread object. This means that the thread's interruption is caused by another thread calling the interrupt() method.

The Thread class provides three interrupt methods:

  • void interrupt() - Interrupt the thread.
  • static boolean interrupted() - Tests whether the current thread is interrupted.
  • boolean isInterrupted() - Tests whether the thread is 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()<strong> </strong>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;
         }
      }
   }
}
Copy after login

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
Copy after login

The above is the detailed content of How to interrupt a running thread in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template