首页 > Java > java教程 > 正文

如何在Java中中断正在运行的线程?

WBOY
发布: 2023-09-18 13:49:02
转载
870 人浏览过

如何在Java中中断正在运行的线程?

线程可以通过调用线程对象的 interrupt() 方法来发送中断信号,从而中断线程。这意味着线程的中断是由其他线程调用 interrupt() 方法引起的。

Thread 类提供了三个中断方法:

  • void interrupt() - 中断线程。
  • static boolean interrupted() - 测试当前线程是否被中断。
  • boolean isInterrupted() - 测试线程是否被中断。

示例

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;
         }
      }
   }
}
登录后复制

输出

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
登录后复制

以上是如何在Java中中断正在运行的线程?的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板