java isinterrupted_JAVA多线程之中断机制stop()、interrupted()、isInterrupted()
一,介绍
本文记录JAVA多线程中的中断机制的一些知识点。主要是stop方法、interrupted()与isInterrupted()方法的区别,并从源代码的实现上进行简单分析。
JAVA中有3种方式可以终止正在运行的线程
①线程正常退出,即run()方法执行完毕了
②使用Thread类中的stop()方法强行终止线程。但stop()方法已经过期了,不推荐使用
③使用中断机制
线程正常退出没有什么东东,中断机制下面详细介绍,先看下stop()方法的源代码,关键是源代码上的注释。它解释了为什么stop()不安全,stop()方法停止的是哪个线程?
/**
* Forces the thread to stop executing.
*
* If there is a security manager installed, its checkAccess
* method is called with this
* as its argument. This may result in a
* SecurityException
being raised (in the current thread).
*
* 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 checkPermission
method (with a
* RuntimePermission("stopThread")
argument) is called in
* addition.
* Again, this may result in throwing a
* SecurityException
(in the current thread).
*
* The thread represented by this thread is forced to stop whatever
* it is doing abnormally and to throw a newly created
* ThreadDeath
object as an exception.
*
* It is permitted to stop a thread that has not yet been started.
* If the thread is eventually started, it immediately terminates.
*
* An application should not normally try to catch
* ThreadDeath
unless it must do some extraordinary
* cleanup operation (note that the throwing of
* ThreadDeath
causes finally
clauses of
* try
statements to be executed before the thread
* officially dies). If a catch
clause catches a
* ThreadDeath
object, it is important to rethrow the
* object so that the thread actually dies.
*
* 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
* ThreadDeath
.
*
* @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
* ThreadDeath
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 stop
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 interrupt
method should be used to
* interrupt the wait.
* For more information, see
* Why
* are Thread.stop, Thread.suspend and Thread.resume Deprecated?.
*/
@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
* interrupted status 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).
*
*
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 true
if the current thread has been interrupted;
* false
otherwise.
* @see #isInterrupted()
* @revised .
*/
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
从源码的注释中看出,它测试的是当前线程(current thread)的中断状态,且这个方法会清除中断状态。
②isInterrupted()
/**
* Tests whether this thread has been interrupted. The interrupted
* status of the thread is unaffected by this method.
*
*
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 true
if this thread has been interrupted;
* false
otherwise.
* @see #interrupted()
* @revised .
*/
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 = ; i < ; i++) {
System.out.println("i=" + (i + ));
}
}
}
先看interrupted()方法的示例:
public class Run {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep();
thread.interrupt();
//Thread.currentThread().interrupt();
System.out.println("是否停止?="+thread.interrupted());//false
System.out.println("是否停止?="+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 Run {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep();
thread.interrupt();
System.out.println("是否停止?="+thread.isInterrupted());//true
在第8行,是thread对象调用的isInterrupted()方法。因此,测试的是thread对象所代表的线程的中断状态。由于在第7行,main线程请求中断 thread线程,故在第8行的结果为: true
java isinterrupted_JAVA多线程之中断机制stop()、interrupted()、isInterrupted()相关推荐
- java isinterrupted_JAVA多线程之中断机制(stop()、interrupted()、isInterrupted())
一,介绍 本文记录JAVA多线程中的中断机制的一些知识点.主要是stop方法.interrupted()与isInterrupted()方法的区别,并从源代码的实现上进行简单分析. JAVA中有3种方 ...
- java面试题成都_成都汇智动力-java面试——多线程面试题
原标题:成都汇智动力-java面试--多线程面试题 1.多线程有什么用?发挥多核CPU的优势 防止阻塞 便于建模 2.创建线程的方式继承Thread类 实现Runnable接口 至于哪个好,不用说肯定 ...
- 第十章 进程间的通信 之 Java/Android多线程开发(二)
文章目录 (一)Java 多线程开发 1.1)线程状态 1.2)线程控制方法 (1.2.1)Synchronized (1.2.2)Volatile (1.2.3)ReentrantLock 1.3) ...
- Java并发指南17:Java常见多线程面试题及答案
Java多线程面试题及答案(2020版) 前言 个人珍藏的80道Java多线程/并发经典面试题,因为篇幅太长,现在先给出1-10的答案解析哈,后面一起完善~ 1. synchronized的实现原理以 ...
- Java面试-多线程并发篇
1. 说说Java中实现多线程有几种方法 创建线程的常用三种方式: 1. 继承Thread类 2. 实现Runnable接口 3. 实现Callable接口 4. 线程池方式创建 通过继承Thread ...
- java 多线程统计质数,Java 七 多线程计算某个范围内的质数
Java 7 多线程计算某个范围内的质数 不多说了,看代码 通用类 package java7.concurrency.math; /** * This class generates prime n ...
- java 创建多线程_Java创建多线程
Java创建多线程 下一节> 到目前为止,我们仅用到两个线程:主线程和一个子线程.然而,你的程序可以创建所需的更多线程.例如,下面的程序创建了三个子线程: // Create multiple ...
- Java的多线程机制系列:(四)不得不提的volatile及指令重排序(happen-before)
一.不得不提的volatile volatile是个很老的关键字,几乎伴随着JDK的诞生而诞生,我们都知道这个关键字,但又不太清楚什么时候会使用它:我们在JDK及开源框架中随处可见这个关键字,但并发专 ...
- Java之多线程买票程序
Java之多线程买票程序 1.要求 要求五个线程,分别命名为售票窗口1.售票窗口 2.......售票窗口5, 一共100张票,每个售票窗口卖票的数量大致相同(20)张卖票时给与编号,每张票唯一. 每 ...
最新文章
- 微信小程序引入字体图标
- Github代码上传和下载
- 李笑来 css,李笑来都想投资千万美金的ACSS通证即将强势登陆奇点交易所
- 技术干货 | Docker容器中需要避免的十种常见误区
- synchronized 异常_面试官,别挂电话,Synchronized,我还能说上半小时
- php json 小红点,关于PHP的json_encode的一个小技巧
- C/C++的memset函数的说明和使用
- git 报错 Repository Not Found
- HDU 3832 Earth Hour
- 最透彻的关于“随机数种子”和“伪随机数”的产生原理
- 计算机win7卡顿如何解决方法,win7系统运行卡顿的解决方法
- 直播源 列表 转换 php,Telelist电视直播源列表创建、转换工具
- 基于javaSwing、MySQL的酒店客房管理系统(附源码)
- centos7 关闭自动yum更新
- tooth的用法_tooth的复数和用法例句
- 超微x9dai 跳线_秒变MacPro!至强E5双路CPU,超微X9DAi主板,Quadro K5000黑苹果
- 商业落地的 DeFi 热潮中,公链们或殊途而同归
- 小白记录:1、scrapy的基础操作
- 微软服务器操作系统软件价格,供应微软服务器操作系统软件
- 【Flutter】GridView的使用之GridView.extent
热门文章
- 【windows】Qt打开资源管理器并选中指定文件
- 计组第一章(唐朔飞)——计算机系统概述章节总结
- django orm级联_Django数据表关联关系映射(一对一、一对多、多对多)
- STM32 之十一 LL 库(low-layer drivers)详解 及 移植说明
- C/C++之类的前置声明
- Linux / 惊群效应
- linux socket API / listen() 两个队列以及第 2 个参数的作用
- BTS3410G参数
- 直流电源端口雷击或瞬态浪涌防护设计方案图详解
- html分为哪两种,css伪类分为哪几种