一,介绍

本文记录JAVA多线程中的中断机制的一些知识点。主要是stop方法、interrupted()与isInterrupted()方法的区别,并从源代码的实现上进行简单分析。

JAVA中有3种方式可以终止正在运行的线程

①线程正常退出,即run()方法执行完毕了

②使用Thread类中的stop()方法强行终止线程。但stop()方法已经过期了,不推荐使用

③使用中断机制

线程正常退出没有什么东东,中断机制下面详细介绍,先看下stop()方法的源代码,关键是源代码上的注释。它解释了为什么stop()不安全,stop()方法停止的是哪个线程?

     /**
* Forces the thread to stop executing.
* <p>
* If there is a security manager installed, its <code>checkAccess</code>
* method is called with <code>this</code>
* as its argument. This may result in a
* <code>SecurityException</code> being raised (in the current thread).
* <p>
* If this thread is different from the current thread (that is, the current
* thread is trying to stop a thread other than itself), the
* security manager's <code>checkPermission</code> method (with a
* <code>RuntimePermission("stopThread")</code> argument) is called in
* addition.
* Again, this may result in throwing a
* <code>SecurityException</code> (in the current thread).
* <p>
* The thread represented by this thread is forced to stop whatever
* it is doing abnormally and to throw a newly created
* <code>ThreadDeath</code> object as an exception.
* <p>
* It is permitted to stop a thread that has not yet been started.
* If the thread is eventually started, it immediately terminates.
* <p>
* An application should not normally try to catch
* <code>ThreadDeath</code> unless it must do some extraordinary
* cleanup operation (note that the throwing of
* <code>ThreadDeath</code> causes <code>finally</code> clauses of
* <code>try</code> statements to be executed before the thread
* officially dies). If a <code>catch</code> clause catches a
* <code>ThreadDeath</code> object, it is important to rethrow the
* object so that the thread actually dies.
* <p>
* The top-level error handler that reacts to otherwise uncaught
* exceptions does not print out a message or otherwise notify the
* application if the uncaught exception is an instance of
* <code>ThreadDeath</code>.
*
* @exception SecurityException if the current thread cannot
* modify this thread.
* @see #interrupt()
* @see #checkAccess()
* @see #run()
* @see #start()
* @see ThreadDeath
* @see ThreadGroup#uncaughtException(Thread,Throwable)
* @see SecurityManager#checkAccess(Thread)
* @see SecurityManager#checkPermission
* @deprecated This method is inherently unsafe. Stopping a thread with
* Thread.stop causes it to unlock all of the monitors that it
* has locked (as a natural consequence of the unchecked
* <code>ThreadDeath</code> exception propagating up the stack). If
* any of the objects previously protected by these monitors were in
* an inconsistent state, the damaged objects become visible to
* other threads, potentially resulting in arbitrary behavior. Many
* uses of <code>stop</code> should be replaced by code that simply
* modifies some variable to indicate that the target thread should
* stop running. The target thread should check this variable
* regularly, and return from its run method in an orderly fashion
* if the variable indicates that it is to stop running. If the
* target thread waits for long periods (on a condition variable,
* for example), the <code>interrupt</code> method should be used to
* interrupt the wait.
* For more information, see
* <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
* are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
*/
@Deprecated
public final void stop() {
stop(new ThreadDeath());
}

上面注释,第9行到第16行表明,stop()方法可以停止“其他线程”。执行thread.stop()方法这条语句的线程称为当前线程,而“其他线程”则是 调用thread.stop()方法的对象thread所代表的线程。

如:

     public static void main(String[] args) {
MyThread thread = new MyThread...
//.....
thread.stop();
//....
}

在main方法中,当前线程就是main线程。它执行到第4行,想把“其他线程”thread“ 给停止。这个其他线程就是MyThread类 new 的thread对象所表示的线程。

第21行至23行表明,可以停止一个尚未started(启动)的线程。它的效果是:当该线程启动后,就立马结束了。

第48行以后的注释,则深刻表明了为什么stop()方法被弃用!为什么它是不安全的。

比如说,threadA线程拥有了监视器,这些监视器负责保护某些临界资源,比如说银行的转账的金额。当正在转账过程中,main线程调用 threadA.stop()方法。结果导致监视器被释放,其保护的资源(转账金额)很可能出现不一致性。比如,A账户减少了100,而B账户却没有增加100

二,中断机制

JAVA中如何正确地使用中断机制的细节太多了。interrupted()方法与 isInterrupted()方法都是反映当前线程的是否处于中断状态的。

①interrupted()

     /**
* Tests whether the current thread has been interrupted. The
* <i>interrupted status</i> of the thread is cleared by this method. In
* other words, if this method were to be called twice in succession, the
* second call would return false (unless the current thread were
* interrupted again, after the first call had cleared its interrupted
* status and before the second call had examined it).
*
* <p>A thread interruption ignored because a thread was not alive
* at the time of the interrupt will be reflected by this method
* returning false.
*
* @return <code>true</code> if the current thread has been interrupted;
* <code>false</code> otherwise.
* @see #isInterrupted()
* @revised 6.0
*/
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}

从源码的注释中看出,它测试的是当前线程(current thread)的中断状态,且这个方法会清除中断状态。

②isInterrupted()

     /**
* Tests whether this thread has been interrupted. The <i>interrupted
* status</i> of the thread is unaffected by this method.
*
* <p>A thread interruption ignored because a thread was not alive
* at the time of the interrupt will be reflected by this method
* returning false.
*
* @return <code>true</code> if this thread has been interrupted;
* <code>false</code> otherwise.
* @see #interrupted()
* @revised 6.0
*/
public boolean isInterrupted() {
return isInterrupted(false);
}

从源码注释中可以看出,isInterrupted()方法不会清除中断状态。

③interrupted()方法与 isInterrupted()方法的区别

从源代码可以看出,这两个方法都是调用的isInterrupted(boolean ClearInterrupted),只不过一个带的参数是true,另一个带的参数是false。

     /**
* Tests if some Thread has been interrupted. The interrupted state
* is reset or not based on the value of ClearInterrupted that is
* passed.
*/
private native boolean isInterrupted(boolean ClearInterrupted);

因此,第一个区别就是,一个会清除中断标识位,另一个不会清除中断标识位。

再分析源码,就可以看出第二个区别在return 语句上:

    public static boolean interrupted() {
return currentThread().isInterrupted(true);
} /************************/
public boolean isInterrupted() {
return isInterrupted(false);
}

interrupted()测试的是当前的线程的中断状态。而isInterrupted()测试的是调用该方法的对象所表示的线程。一个是静态方法(它测试的是当前线程的中断状态),一个是实例方法(它测试的是实例对象所表示的线程的中断状态)。

下面用个具体的例子来更进一步地阐明这个区别。

有一个自定义的线程类如下:

 public class MyThread extends Thread {
@Override
public void run() {
super.run();
for (int i = 0; i < 500000; i++) {
System.out.println("i=" + (i + 1));
}
}
}

先看interrupted()方法的示例:

 public class Run {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(1000);
thread.interrupt();
//Thread.currentThread().interrupt();
System.out.println("是否停止1?="+thread.interrupted());//false
System.out.println("是否停止2?="+thread.interrupted());//false main线程没有被中断!!!
      //......

第5行启动thread线程,第6行使main线程睡眠1秒钟从而使得thread线程有机会获得CPU执行。

main线程睡眠1s钟后,恢复执行到第7行,请求中断 thread线程。

第9行测试线程是否处于中断状态,这里测试的是哪个线程呢???答案是main线程。因为:

(1)interrupted()测试的是当前的线程的中断状态

(2)main线程执行了第9行语句,故main线程是当前线程

再看isInterrupted()方法的示例:

 public class Run3 {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(1000);
thread.interrupt();
System.out.println("是否停止1?="+thread.isInterrupted());//true

在第8行,是thread对象调用的isInterrupted()方法。因此,测试的是thread对象所代表的线程的中断状态。由于在第7行,main线程请求中断 thread线程,故在第8行的结果为: true

JAVA多线程之中断机制(stop()、interrupted()、isInterrupted())的更多相关文章

  1. JAVA多线程之中断机制(如何处理中断?)

    一,介绍 这篇文章主要记录使用 interrupt() 方法中断线程,以及如何对InterruptedException进行处理.感觉对InterruptedException异常进行处理是一件谨慎且 ...

  2. Java多线程——中断机制

    前言:在Java多线程中,中断一直围绕着我们,当我们阅读各种关于Java多线程的资料.书籍时,“中断”一词总是会出现,笔者对其的理解也是朦朦胧胧,因此非常有必要搞清楚Java多线程的中断机制. 1.J ...

  3. 50个Java多线程面试题

    不管你是新程序员还是老手,你一定在面试中遇到过有关线程的问题.Java 语言一个重要的特点就是内置了对并发的支持,让 Java 大受企业和程序员的欢迎.大多数待遇丰厚的 Java 开发职位都要求开发者 ...

  4. 50个Java多线程面试题(上)

    Java 语言一个重要的特点就是内置了对并发的支持,让 Java 大受企业和程序员的欢迎.大多数待遇丰厚的 Java 开发职位都要求开发者精通多线程技术并且有丰富的 Java 程序开发.调试.优化经验 ...

  5. Java多线程与并发面试题

    1,什么是线程? 线程是操作系统能够进行运算调度的最小单位,它被包含在进程之中,是进程中的实际运作单位.程序员可以通过它进行多处理器编程,你可以使用多线程对运算密集型任务提速.比如,如果一个线程完成一 ...

  6. Java多线程面试题整理

    部分一:多线程部分: 1) 什么是线程? 线程是操作系统能够进行运算调度的最小单位,它被包含在进程之中,是进程中的实际运作单位.程序员可以通过它进行多处理器编程,你可以使用多线程对运算密集型任务提速. ...

  7. JAVA多线程17个问题

    1.Thread 类中的start() 和 run() 方法有什么区别? Thread.start()方法(native)启动线程,使之进入就绪状态,当cpu分配时间该线程时,由JVM调度执行run( ...

  8. java多线程面试题整理及答案(2018年)

    1) 什么是线程? 线程是操作系统能够进行运算调度的最小单位,它被包含在进程之中,是进程中的实际运作单位.程序员可以通过它进行多处理器编程,你可以使用多线程对 运算密集型任务提速.比如,如果一个线程完 ...

  9. Java 多线程 - 转载

    下面是Java线程相关的热门面试题,你可以用它来好好准备面试. 1) 什么是线程? 线程是操作系统能够进行运算调度的最小单位,它被包含在进程之中,是进程中的实际运作单位.程序员可以通过它进行多处理器编 ...

随机推荐

  1. 密码安全存储——PBKDF2、bcrypt、scrypt

    密码用单向哈希存储保证了数据库被脱后用户密码的安全. 由于彩虹表这种攻击方式的存在,一般认为md5,SHA1等单向算法的安全性是不够的.那如何选择合适的加密算法? 下面介绍业界几种高强度单向哈希算法, ...

  2. spark-streaming first insight

    一. Spark Streaming 构建在Spark core API之上,具备可伸缩,高吞吐,可容错的流处理模块. 1)支持多种数据源,如Kafka,Flume,Socket,文件等: Basic ...

  3. Django之模版层-语法:标签 {% %}

    标签 {% %} for循环以及for..empty.. <h4>for标签</h4> {% for i in lis %} <p>{{ i }}</p> ...

  4. socket模块粘包现象理解以及解决思路

    粘包现象: 在socket网络程序中,TCP和UDP分别是面向连接和非面向连接的.因此TCP的socket编程,收发两端(客户端和服务器端)都要有成对的socket,因此,发送端为了将多个发往接收端的 ...

  5. Python用re正则化模块在字符串查找特定字符串

    实验需要,在一个含有几亿个字符的txt文件中查找特定的字符串,首先用re模块进行查找 from time import clock import re start=clock() label_file ...

  6. Windows 下使用nginx命令启动

    http://wanganwu.blog.163.com/blog/static/7788722012322111417966/ Windows下Nginx的启动.停止等命令 在Windows下使用N ...

  7. 20155219 2016-2017-2 《Java程序设计》第4周学习总结

    20155219 2016-2017-2 <Java程序设计>第4周学习总结 教材学习内容总结 抽象方法与抽象类 如果某方法区块中没有任何程序代码操作,可以使用abstract在class ...

  8. guling code细节

    detect_hand.py 分水岭算法: 任何一幅灰度图像都可以被看成拓扑平面,灰度值高的区域可以被看成是山峰,灰度值低的区域可以被看成是山谷.我们向每一个山谷中灌不同颜色的水,随着水的位的升高,不 ...

  9. 51Nod 1070:Bash游戏 V4(斐波那契博弈)

    1070 Bash游戏 V4  基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题  收藏  关注 有一堆石子共有N个.A B两个人轮流拿,A先拿.每次拿的数量最少1个 ...

  10. 启动服务报错:nested exception is java.lang.NoSuchMethodError: org.apache.cxf.common.jaxb.JAXBUtils.closeUnmarshaller(Ljavax/xml/bind/Unmarshaller;)V

    1.启动tomcat时报错:Error creating bean with name 'payInfService': Invocation of init method failed; neste ...