JAVA多线程之中断机制(stop()、interrupted()、isInterrupted())

简介:

一,介绍

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

 

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

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

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

③使用中断机制

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

复制代码
 1     /**
 2      * Forces the thread to stop executing.
 3      * <p>
 4      * If there is a security manager installed, its <code>checkAccess</code>
 5      * method is called with <code>this</code>
 6      * as its argument. This may result in a
 7      * <code>SecurityException</code> being raised (in the current thread).
 8      * <p>
 9      * If this thread is different from the current thread (that is, the current
10      * thread is trying to stop a thread other than itself), the
11      * security manager's <code>checkPermission</code> method (with a
12      * <code>RuntimePermission("stopThread")</code> argument) is called in
13      * addition.
14      * Again, this may result in throwing a
15      * <code>SecurityException</code> (in the current thread).
16      * <p>
17      * The thread represented by this thread is forced to stop whatever
18      * it is doing abnormally and to throw a newly created
19      * <code>ThreadDeath</code> object as an exception.
20      * <p>
21      * It is permitted to stop a thread that has not yet been started.
22      * If the thread is eventually started, it immediately terminates.
23      * <p>
24      * An application should not normally try to catch
25      * <code>ThreadDeath</code> unless it must do some extraordinary
26      * cleanup operation (note that the throwing of
27      * <code>ThreadDeath</code> causes <code>finally</code> clauses of
28      * <code>try</code> statements to be executed before the thread
29      * officially dies).  If a <code>catch</code> clause catches a
30      * <code>ThreadDeath</code> object, it is important to rethrow the
31      * object so that the thread actually dies.
32      * <p>
33      * The top-level error handler that reacts to otherwise uncaught
34      * exceptions does not print out a message or otherwise notify the
35      * application if the uncaught exception is an instance of
36      * <code>ThreadDeath</code>.
37      *
38      * @exception  SecurityException  if the current thread cannot
39      *               modify this thread.
40      * @see        #interrupt()
41      * @see        #checkAccess()
42      * @see        #run()
43      * @see        #start()
44      * @see        ThreadDeath
45      * @see        ThreadGroup#uncaughtException(Thread,Throwable)
46      * @see        SecurityManager#checkAccess(Thread)
47      * @see        SecurityManager#checkPermission
48      * @deprecated This method is inherently unsafe.  Stopping a thread with
49      *       Thread.stop causes it to unlock all of the monitors that it
50      *       has locked (as a natural consequence of the unchecked
51      *       <code>ThreadDeath</code> exception propagating up the stack).  If
52      *       any of the objects previously protected by these monitors were in
53      *       an inconsistent state, the damaged objects become visible to
54      *       other threads, potentially resulting in arbitrary behavior.  Many
55      *       uses of <code>stop</code> should be replaced by code that simply
56      *       modifies some variable to indicate that the target thread should
57      *       stop running.  The target thread should check this variable
58      *       regularly, and return from its run method in an orderly fashion
59      *       if the variable indicates that it is to stop running.  If the
60      *       target thread waits for long periods (on a condition variable,
61      *       for example), the <code>interrupt</code> method should be used to
62      *       interrupt the wait.
63      *       For more information, see
64      *       <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
65      *       are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
66      */
67     @Deprecated
68     public final void stop() {
69         stop(new ThreadDeath());
70     }
复制代码

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

如:

1     public static void main(String[] args) {
2         MyThread thread = new MyThread...
3         //.....
4         thread.stop();
5         //....
6     }

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

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

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

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

 

二,中断机制

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

①interrupted()

复制代码
 1     /**
 2      * Tests whether the current thread has been interrupted.  The
 3      * <i>interrupted status</i> of the thread is cleared by this method.  In
 4      * other words, if this method were to be called twice in succession, the
 5      * second call would return false (unless the current thread were
 6      * interrupted again, after the first call had cleared its interrupted
 7      * status and before the second call had examined it).
 8      *
 9      * <p>A thread interruption ignored because a thread was not alive
10      * at the time of the interrupt will be reflected by this method
11      * returning false.
12      *
13      * @return  <code>true</code> if the current thread has been interrupted;
14      *          <code>false</code> otherwise.
15      * @see #isInterrupted()
16      * @revised 6.0
17      */
18     public static boolean interrupted() {
19         return currentThread().isInterrupted(true);
20     }
复制代码

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

 

②isInterrupted()

复制代码
 1     /**
 2      * Tests whether this thread has been interrupted.  The <i>interrupted
 3      * status</i> of the thread is unaffected by this method.
 4      *
 5      * <p>A thread interruption ignored because a thread was not alive
 6      * at the time of the interrupt will be reflected by this method
 7      * returning false.
 8      *
 9      * @return  <code>true</code> if this thread has been interrupted;
10      *          <code>false</code> otherwise.
11      * @see     #interrupted()
12      * @revised 6.0
13      */
14     public boolean isInterrupted() {
15         return isInterrupted(false);
16     }
复制代码

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

 

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

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

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

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

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

复制代码
    public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }

    /************************/
    public boolean isInterrupted() {
        return isInterrupted(false);
    }
复制代码

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

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

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

复制代码
1 public class MyThread extends Thread {
2     @Override
3     public void run() {
4         super.run();
5         for (int i = 0; i < 500000; i++) {
6             System.out.println("i=" + (i + 1));
7         }
8     }
9 }
复制代码

 

先看interrupted()方法的示例:

复制代码
 1 public class Run {
 2     public static void main(String[] args) {
 3         try {
 4             MyThread thread = new MyThread();
 5             thread.start();
 6             Thread.sleep(1000);
 7             thread.interrupt();
 8             //Thread.currentThread().interrupt();
 9             System.out.println("是否停止1?="+thread.interrupted());//false
10             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()方法的示例:

复制代码
1 public class Run3 {
2     public static void main(String[] args) {
3         try {
4             MyThread thread = new MyThread();
5             thread.start();
6             Thread.sleep(1000);
7             thread.interrupt();
8             System.out.println("是否停止1?="+thread.isInterrupted());//true
复制代码

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

 本文转自hapjin博客园博客,原文链接:http://www.cnblogs.com/hapjin/p/5450121.html,如需转载请自行联系原作者

相关文章
|
11天前
|
并行计算 安全 Java
Python GIL(全局解释器锁)机制对多线程性能影响的深度分析
在Python开发中,GIL(全局解释器锁)一直备受关注。本文基于CPython解释器,探讨GIL的技术本质及其对程序性能的影响。GIL确保同一时刻只有一个线程执行代码,以保护内存管理的安全性,但也限制了多线程并行计算的效率。文章分析了GIL的必要性、局限性,并介绍了多进程、异步编程等替代方案。尽管Python 3.13计划移除GIL,但该特性至少要到2028年才会默认禁用,因此理解GIL仍至关重要。
66 16
Python GIL(全局解释器锁)机制对多线程性能影响的深度分析
|
1天前
|
安全 Java 开发者
【JAVA】封装多线程原理
Java 中的多线程封装旨在简化使用、提高安全性和增强可维护性。通过抽象和隐藏底层细节,提供简洁接口。常见封装方式包括基于 Runnable 和 Callable 接口的任务封装,以及线程池的封装。Runnable 适用于无返回值任务,Callable 支持有返回值任务。线程池(如 ExecutorService)则用于管理和复用线程,减少性能开销。示例代码展示了如何实现这些封装,使多线程编程更加高效和安全。
|
1天前
|
网络协议 Java Shell
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
21 7
|
2月前
|
Java
Java—多线程实现生产消费者
本文介绍了多线程实现生产消费者模式的三个版本。Version1包含四个类:`Producer`(生产者)、`Consumer`(消费者)、`Resource`(公共资源)和`TestMain`(测试类)。通过`synchronized`和`wait/notify`机制控制线程同步,但存在多个生产者或消费者时可能出现多次生产和消费的问题。 Version2将`if`改为`while`,解决了多次生产和消费的问题,但仍可能因`notify()`随机唤醒线程而导致死锁。因此,引入了`notifyAll()`来唤醒所有等待线程,但这会带来性能问题。
Java—多线程实现生产消费者
|
1月前
|
缓存 安全 算法
Java 多线程 面试题
Java 多线程 相关基础面试题
|
2月前
|
安全 Java Kotlin
Java多线程——synchronized、volatile 保障可见性
Java多线程中,`synchronized` 和 `volatile` 关键字用于保障可见性。`synchronized` 保证原子性、可见性和有序性,通过锁机制确保线程安全;`volatile` 仅保证可见性和有序性,不保证原子性。代码示例展示了如何使用 `synchronized` 和 `volatile` 解决主线程无法感知子线程修改共享变量的问题。总结:`volatile` 确保不同线程对共享变量操作的可见性,使一个线程修改后,其他线程能立即看到最新值。
|
2月前
|
消息中间件 缓存 安全
Java多线程是什么
Java多线程简介:本文介绍了Java中常见的线程池类型,包括`newCachedThreadPool`(适用于短期异步任务)、`newFixedThreadPool`(适用于固定数量的长期任务)、`newScheduledThreadPool`(支持定时和周期性任务)以及`newSingleThreadExecutor`(保证任务顺序执行)。同时,文章还讲解了Java中的锁机制,如`synchronized`关键字、CAS操作及其实现方式,并详细描述了可重入锁`ReentrantLock`和读写锁`ReadWriteLock`的工作原理与应用场景。
|
2月前
|
存储 安全 Java
Java多线程编程秘籍:各种方案一网打尽,不要错过!
Java 中实现多线程的方式主要有四种:继承 Thread 类、实现 Runnable 接口、实现 Callable 接口和使用线程池。每种方式各有优缺点,适用于不同的场景。继承 Thread 类最简单,实现 Runnable 接口更灵活,Callable 接口支持返回结果,线程池则便于管理和复用线程。实际应用中可根据需求选择合适的方式。此外,还介绍了多线程相关的常见面试问题及答案,涵盖线程概念、线程安全、线程池等知识点。
217 2
|
2月前
|
安全 算法 Java
Java多线程编程中的陷阱与最佳实践####
本文探讨了Java多线程编程中常见的陷阱,并介绍了如何通过最佳实践来避免这些问题。我们将从基础概念入手,逐步深入到具体的代码示例,帮助开发者更好地理解和应用多线程技术。无论是初学者还是有经验的开发者,都能从中获得有价值的见解和建议。 ####
|
2月前
|
Java 调度
Java中的多线程编程与并发控制
本文深入探讨了Java编程语言中多线程编程的基础知识和并发控制机制。文章首先介绍了多线程的基本概念,包括线程的定义、生命周期以及在Java中创建和管理线程的方法。接着,详细讲解了Java提供的同步机制,如synchronized关键字、wait()和notify()方法等,以及如何通过这些机制实现线程间的协调与通信。最后,本文还讨论了一些常见的并发问题,例如死锁、竞态条件等,并提供了相应的解决策略。
71 3