一,介绍
本文记录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 . */ 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 . */ 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
由于使用stop()方法停止线程非常的暴力,人家线程运行的好好的,突然就把人家杀死了,线程占用的锁被强制释放,极易导致数据的不一致性。因此,提出了一种温和的方式:请求另外一个线程不要再执行了,这就是中断方式。 假设某个线程要不停地处理某件事情(比如 i 一直自增),但是还有个要求:在处理事情前,先要检查下这个线程是否被中断,如果已经被中断,处理就应该结束。 public class Run {
本文向大家介绍Java多线程 中断机制及实例详解,包括了Java多线程 中断机制及实例详解的使用技巧和注意事项,需要的朋友参考一下 正文 这里详细分析interrupt(),interrupted(),isInterrupted()三个方法 interrupt() 中断这个线程,设置中断标识位 我们来找下如何设置中断标识位的 找到interrupt0()的源码,src/hotspot/share/
我有以下代码: 不会中断线程,它会继续运行。如果我替换和,然后线程停止。但是,已弃用。那么,如果不推荐使用,而don't work,那么停止线程的正确方法是什么?
问题内容: 以下代码是我的应用中的服务器代码: 代码工作方式,即如果我尝试直接连接,则两端进行通信和更新。 问题是即时通讯正在侦听连接,如果我想退出侦听,则服务器线程会继续运行并导致问题。 我知道我不应该在线程上使用.stop(),所以我想知道解决方案的外观如何? 编辑:注释掉不需要的代码。 问题答案: 从外部线程关闭服务器套接字。根据Serversocket.close()上的文档,阻塞接受将抛
前面我们介绍过Chromium是基于多进程模型的架构设计,那么各个进程内的情况呢?事实是每个进程都有很多的线程,特别是browser进程,因而它也基于多线程模型的。介绍多线程机制之前,先来看一下残酷的现实吧,下面是各个进程的线程信息情况(基于Linux平台,其它平台的可能略有不同),相信保证让你头大。是的,你需要泡杯茶,然后静下心来了解一下它们: 为什么这么多的线程呢?Chromium的官方说法告
本文向大家介绍Java多线程之异步Future机制的原理和实现,包括了Java多线程之异步Future机制的原理和实现的使用技巧和注意事项,需要的朋友参考一下 项目中经常有些任务需要异步(提交到线程池中)去执行,而主线程往往需要知道异步执行产生的结果,这时我们要怎么做呢?用runnable是无法实现的,我们需要用callable看下面的代码: 虽然可以实现获取异步执行结果的需求,但是我们发现这个F