在上篇文章《多线程的使用——Thread类和Runnable接口》中提到中断线程的问题。在JAVA中,曾经使用stop方法来停止线程,然而,该方法具有固有的不安全性,因而已经被抛弃(Deprecated)。那么应该怎么结束一个进程呢?官方文档中对此有详细说明:《为何不赞成使用 Thread.stop、Thread.suspend 和 Thread.resume?》。在此引用stop方法的说明:
1. Why is Thread.stop deprecated?
Because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked. (The monitors are unlocked as the ThreadDeath exception propagates up the stack.) If any of the objects previously protected by these monitors were in an inconsistent state, other threads may now view these objects in an inconsistent state. Such objects are said to be damaged. When threads operate on damaged objects, arbitrary behavior can result. This behavior may be subtle and difficult to detect, or it may be pronounced. Unlike other unchecked exceptions, ThreadDeath kills threads silently; thus, the user has no warning that his program may be corrupted. The corruption can manifest itself at any time after the actual damage occurs, even hours or days in the future.
大概意思是:
因为该方法本质上是不安全的。停止一个线程将释放它已经锁定的所有监视器(作为沿堆栈向上传播的未检查 ThreadDeath 异常的一个自然后果)。如果以前受这些监视器保护的任何对象都处于一种不一致的状态,则损坏的对象将对其他线程可见,这有可能导致任意的行为。此行为可能是微妙的,难以察觉,也可能是显著的。不像其他的未检查异常,ThreadDeath异常会在后台杀死线程,因此,用户并不会得到警告,提示他的程序可能已损坏。这种损坏有可能在实际破坏发生之后的任何时间表现出来,也有可能在多小时甚至在未来的很多天后。
在文档中还提到,程序员不能通过捕获ThreadDeath异常来修复已破坏的对象。具体原因见原文。
既然stop方法不建议使用,那么应该用什么方法来代理stop已实现相应的功能呢?
1、通过修改共享变量来通知目标线程停止运行
大部分需要使用stop的地方应该使用这种方法来达到中断线程的目的。
这种方法有几个要求或注意事项:
(1)目标线程必须有规律的检查变量,当该变量指示它应该停止运行时,该线程应该按一定的顺序从它执行的方法中返回。
(2)该变量必须定义为volatile,或者所有对它的访问必须同步(synchronized)。
例如:
假如你的applet包括start,stop,run几个方法:
private Thread blinker;
public void start() {
blinker = new Thread(this);
blinker.start();
}
public void stop() {
blinker.stop(); // UNSAFE!
}
public void run() {
Thread thisThread = Thread.currentThread();
while (true) {
try {
thisThread.sleep(interval);
} catch (InterruptedException e){
}
repaint();
}
}
你可以使用如下方式避免使用Thread.stop方法:
private volatile Thread blinker;
public void stop() {
blinker = null;
}
public void run() {
Thread thisThread = Thread.currentThread();
while (blinker == thisThread) {
try {
thisThread.sleep(interval);
} catch (InterruptedException e){
}
repaint();
}
}
2、通过Thread.interrupt方法中断线程
通常情况下,我们应该使用第一种方式来代替Thread.stop方法。然而以下几种方式应该使用Thread.interrupt方法来中断线程(该方法通常也会结合第一种方法使用)。
一开始使用interrupt方法时,会有莫名奇妙的感觉:难道该方法有问题?
API文档上说,该方法用于"Interrupts this thread"。请看下面的例子:
package com.polaris.thread;
public class TestThread implements Runnable{
boolean stop = false;
public static void main(String[] args) throws Exception {
Thread thread = new Thread(new TestThread(),"My Thread");
System.out.println( "Starting thread..." );
thread.start();
Thread.sleep( 3000 );
System.out.println( "Interrupting thread..." );
thread.interrupt();
System.out.println("线程是否中断:" + thread.isInterrupted());
Thread.sleep( 3000 );
System.out.println("Stopping application..." );
}
public void run() {
while(!stop){
System.out.println( "My Thread is running..." );
// 让该循环持续一段时间,使上面的话打印次数少点
long time = System.currentTimeMillis();
while((System.currentTimeMillis()-time < 1000)) {
}
}
System.out.println("My Thread exiting under request..." );
}
}
运行后的结果是:
Starting thread...
My Thread is running...
My Thread is running...
My Thread is running...
My Thread is running...
Interrupting thread...
线程是否中断:true
My Thread is running...
My Thread is running...
My Thread is running...
Stopping application...
My Thread is running...
My Thread is running...
……
应用程序并不会退出,启动的线程没有因为调用interrupt而终止,可是从调用isInterrupted方法返回的结果可以清楚地知道该线程已经中断了。那位什么会出现这种情况呢?到底是interrupt方法出问题了还是isInterrupted方法出问题了?在Thread类中还有一个测试中断状态的方法(静态的)interrupted,换用这个方法测试,得到的结果是一样的。由此似乎应该是interrupt方法出问题了。于是,在网上有一篇文章:《 Java Thread.interrupt 害人! 中断JAVA线程》,它详细的说明了应该如何使用interrupt来中断一个线程的执行。
实际上,在JAVA API文档中对该方法进行了详细的说明。该方法实际上只是设置了一个中断状态,当该线程由于下列原因而受阻时,这个中断状态就起作用了:
(1)如果线程在调用 Object 类的 wait()、wait(long) 或 wait(long, int) 方法,或者该类的 join()、join(long)、join(long, int)、sleep(long) 或 sleep(long, int) 方法过程中受阻,则其中断状态将被清除,它还将收到一个InterruptedException异常。这个时候,我们可以通过捕获InterruptedException异常来终止线程的执行,具体可以通过return等退出或改变共享变量的值使其退出。
(2)如果该线程在可中断的通道上的 I/O 操作中受阻,则该通道将被关闭,该线程的中断状态将被设置并且该线程将收到一个 ClosedByInterruptException。这时候处理方法一样,只是捕获的异常不一样而已。
其实对于这些情况有一个通用的处理方法:
package com.polaris.thread;
public class TestThread2 implements Runnable{
boolean stop = false;
public static void main(String[] args) throws Exception {
Thread thread = new Thread(new TestThread2(),"My Thread2");
System.out.println( "Starting thread..." );
thread.start();
Thread.sleep( 3000 );
System.out.println( "Interrupting thread..." );
thread.interrupt();
System.out.println("线程是否中断:" + thread.isInterrupted());
Thread.sleep( 3000 );
System.out.println("Stopping application..." );
}
public void run() {
while(!stop){
System.out.println( "My Thread is running..." );
// 让该循环持续一段时间,使上面的话打印次数少点
long time = System.currentTimeMillis();
while((System.currentTimeMillis()-time < 1000)) {
}
if(Thread.currentThread().isInterrupted()) {
return;
}
}
System.out.println("My Thread exiting under request..." );
}
}
因为调用interrupt方法后,会设置线程的中断状态,所以,通过监视该状态来达到终止线程的目的。
总结:程序应该对线程中断作出恰当的响应。响应方式通常有三种:(来自温绍锦(昵称:温少):http//www.cnblogs.com/jobs/)
注意:interrupted与isInterrupted方法的区别(见API文档)
引用一篇文章
来自随心所欲http://redisliu.blog.sohu.com/131647795.html 的Java的interrupt机制
当外部线程对某线程调用了thread.interrupt()方法后,java语言的处理机制如下:
如果该线程处在可中断状态下,(调用了xx.wait(),或者Selector.select(),Thread.sleep()等特定会发生阻塞的api),那么该线程会立即被唤醒,同时会受到一个InterruptedException,同时,如果是阻塞在io上,对应的资源会被关闭。如果该线程接下来不执行“Thread.interrupted()方法(不是interrupt),那么该线程处理任何io资源的时候,都会导致这些资源关闭。当然,解决的办法就是调用一下interrupted(),不过这里需要程序员自行根据代码的逻辑来设定,根据自己的需求确认是否可以直接忽略该中断,还是应该马上退出。
如果该线程处在不可中断状态下,就是没有调用上述api,那么java只是设置一下该线程的interrupt状态,其他事情都不会发生,如果该线程之后会调用行数阻塞API,那到时候线程会马会上跳出,并抛出InterruptedException,接下来的事情就跟第一种状况一致了。如果不会调用阻塞API,那么这个线程就会一直执行下去。除非你就是要实现这样的线程,一般高性能的代码中肯定会有wait(),yield()之类出让cpu的函数,不会发生后者的情况。
- 大小: 33.4 KB
分享到:
相关推荐
ARM Linux中断源码分析(2)——中断处理流程
在学习Java过程中,自己收集了很多的Java的学习资料,分享给大家,有需要的欢迎下载,希望对大家有用,一起学习,一起进步。
interrupt字面上是中断的意思,但在Java里Thread.interrupt()方法实际上通过某种方式通知线程,并不会直接中止该线程
即“线程中断”并不是字面意思——线程真的中断了,而是设置了中断标志位为true。 thread.interrupt() 该方法“中断线程”,但仅仅是会设置该线程的中断状态位为true,至于中断的结果线程是死亡、还是等待新的...
interrupt(),在一个线程中调用另一个线程的interrupt()方法,即会向那个线程发出信号——线程中断状态已被设置。至于那个线程何去何从,由具体的代码实现决定。 isInterrupted(),用来判断当前线程的中断状态...
MCS51 中断interrupt
java线程中断之interrupt和stop.docx
线程的基本概念、线程类、任务类、线程优先级、sleep()方法(休眠)、yield()方法(礼让)、join方法(合并)、interrupt()方法(中断),线程的生命周期 线程 与 进程 的关系:**有一个进程中至少包含一个线程 **...
创建和开始使用多线程 线程同步基础 同步要领 锁和线程安全 Interrupt 和 Abort 线程状态 等待句柄 同步环境 使用多线程 单元模式和Windows Forms BackgroundWorker类 ReaderWriterLock类 线程池 异步委托 计时器 ...
时间,因此效率及其低下,所以一般都是采用第二种方案。 从物理学的角度看,中断是一种电信号,由硬件设备产生,并直接送入中断控制器的输入 引脚上,然后再由中断控制器向处理器发送相应的信号。处理器一经检测到该...
Thread.interrupt()方法的使用以及使用它退出线程
在java中,线程的中断(interrupt)只是改变了线程的中断状态,至于这个中断状态改变后带来的结果,那是无法确定的,有时它更是让停止中的线程继续执行的唯一手段。不但不是让线程停止运行,反而是继续执行线程的...
arduino_esp8266Interrupt中断样例
通俗来说,计算机外设,比如键盘发生事件(比如按下一个键)会通知到CPU, 这时CPU忙完手头的指令,就会转而执行对应的中断程序。 这句话太通俗,太笼统。那么下面细说。
一个线程join另一个线程,(包括和interrupt互动的用法)3---马克-to-win java视频
java线程中的interrupt,isInterrupt,interrupted方法
看完《think in java》多线程章节,自己写的多线程文档,还结合了其他的相关网络资料。 线程 一. 线程池 1)为什么要使用线程池 2 2)一个具有线程池的工作队列 3 3)使用线程池的风险: 4 4)有效使用线程池的原则 5...
一个线程join另一个线程,(包括和interrupt互动的用法)1---马克-to-win java视频
线程的thread.interrupt()方法是中断线程,将会设置该线程的中断状态位,即设置为true,中断的结果线程是死亡、还是等待新的任务或是继续运行至下一步,就取决于这个程序本身。线程会不时地检测这个中断标示位,以...
使用turbo c提供interrupt关键,在每次时间片中断函数时保存现场的功能实现函数之间的切换;加上TCB管理的结构体,实现线程调度。 物理文件的存储结构 引导块区 FAT区 i节点区 数据区 实现的命令集 命令名称 使用...