在 Java 中中断线程 [英] Interrupting a thread in Java

查看:63
本文介绍了在 Java 中中断线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想优雅地关闭线程.我在互联网上看到了很多代码,并在这里查询.我认为有两种关闭方法.

I want to gracefully shutdown the threads. I seen many codes on internet and have query here. I think there are two approaches to shutdown.

  1. 使用布尔标志.一旦标记更改,我们就可以在 run 方法中破坏那里的代码.
  2. 使用中断方法.

我的问题是为什么避免使用布尔标志来优雅地关闭线程,当我运行示例程序时它运行良好.

My question why it is avoided to use boolean flag to gracefully shutdown the threads, When I ran sample program it went well.

推荐答案

boolean 标志没有任何问题,但是:

There is nothing wrong with boolean flag, however:

  • 你需要记住同步/可见性(至少把 volatile 放在标志上)

为什么在已经实现(中断)的情况下添加一个额外的标志?

why adding an extra flag when one is already implemented (interrupted)?

其他库/容器可能会尝试中断您的线程(毕竟,他们不知道您的标志!)所以您仍然需要支持 InterruptedException 和/或 isInterrupted() 标志

Other libraries/containers might try to interrupt your thread (after all, they don't know about your flag!) so you still need to support InterruptedException and/or isInterrupted() flag

中断线程也可以中断 I/O 调用和 Thread.sleep().您的自定义标志不能

interrupting a thread can also interrupt I/O calls and Thread.sleep(). Your custom flag can't

这篇关于在 Java 中中断线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆