Java线程中的interrupt方法解读

 更新时间:2023年10月17日 08:40:35   作者:huskyui  
这篇文章主要介绍了Java线程中的interrupt方法解读,Java中的interrupt是一种线程间通信的机制,用于请求中断线程的执行。当一个线程调用另一个线程的interrupt()方法时,被调用线程会收到一个中断信号,可以根据需要做出相应的处理,需要的朋友可以参考下

interrupt方法

首先梳理Thread关于interrupt的定义

/**
 * Interrupts this thread.
 *
 * <p> Unless the current thread is interrupting itself, which is
 * always permitted, the {@link #checkAccess() checkAccess} method
 * of this thread is invoked, which may cause a {@link
 * SecurityException} to be thrown.
 *
 * <p> If this thread is blocked in an invocation of the {@link
 * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
 * Object#wait(long, int) wait(long, int)} methods of the {@link Object}
 * class, or of the {@link #join()}, {@link #join(long)}, {@link
 * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
 * methods of this class, then its interrupt status will be cleared and it
 * will receive an {@link InterruptedException}.
 *
 * <p> If this thread is blocked in an I/O operation upon an {@link
 * java.nio.channels.InterruptibleChannel InterruptibleChannel}
 * then the channel will be closed, the thread's interrupt
 * status will be set, and the thread will receive a {@link
 * java.nio.channels.ClosedByInterruptException}.
 *
 * <p> If this thread is blocked in a {@link java.nio.channels.Selector}
 * then the thread's interrupt status will be set and it will return
 * immediately from the selection operation, possibly with a non-zero
 * value, just as if the selector's {@link
 * java.nio.channels.Selector#wakeup wakeup} method were invoked.
 *
 * <p> If none of the previous conditions hold then this thread's interrupt
 * status will be set. </p>
 *
 * <p> Interrupting a thread that is not alive need not have any effect.
 *
 * @throws  SecurityException
 *          if the current thread cannot modify this thread
 *
 * @revised 6.0
 * @spec JSR-51
 */
public void interrupt() 

这里讲述了Thread实例对象调用方法interrupt,有这几种情况

? 1.在线程里面有wait,sleep,join方法,会弹出InterruptedException,状态会被清除

? 2.io里面,会弹出异常,状态会被设置,…

? 3.如果线程阻塞在nio中的Selector中,状态会被设置,…

? 4.如果不是上面,这些情况,状态会被设置

可以看出interrupt是关于状态的设置

我们来验证一下

第一种,没有任何情况的

public static void main(String[] args) {
    Thread t1 = new Thread(()->{
       while(true){
           if (interrupted()) {
               break;
           }
           System.out.println("i" + new Date());
       }
    });
    t1.start();
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    t1.interrupt();
}

线程会在(1000+)ms后结束,整个程序也会结束

第二种,有sleep的情况下

public static void main(String[] args) {
    Thread t1 = new Thread(()->{
       while(true){
           if (interrupted()) {
               break;
           }
           try {
               Thread.sleep(100);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }

           System.out.println("i" + new Date());
       }
    });
    t1.start();
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    t1.interrupt();
}

方法并不会退出,只是打出了一个InterruptException

如何处理中断?

  • 上文都在介绍如何获取中断状态,那么当我们捕获到中断状态后,究竟如何处理呢?
  • Java类库中提供的一些可能会发生阻塞的方法都会抛InterruptedException异常,如:BlockingQueue#put、BlockingQueue#take、Object#wait、Thread#sleep。
  • 当你在某一条线程中调用这些方法时,这个方法可能会被阻塞很长时间,你可以在别的线程中调用当前线程对象的interrupt方法触发这些函数抛出InterruptedException异常。
  • 当一个函数抛出InterruptedException异常时,表示这个方法阻塞的时间太久了,别人不想等它执行结束了。
  • 当你的捕获到一个InterruptedException异常后,亦可以处理它,或者向上抛出。
  • 抛出时要注意???:当你捕获到InterruptedException异常后,当前线程的中断状态已经被修改为false(表示线程未被中断);此时你若能够处理中断,则不用理会该值;但如果你继续向上抛InterruptedException异常,你需要再次调用interrupt方法,将当前线程的中断状态设为true。
  • 注意:绝对不能“吞掉中断”!即捕获了InterruptedException而不作任何处理。这样违背了中断机制的规则,别人想让你线程中断,然而你自己不处理,也不将中断请求告诉调用者,调用者一直以为没有中断请求。

更新相关interrupt方法的意义

public void interrupt()

Thread里面的打断函数,可以使用新建一个Thread对象,执行thread.interrupt();

修改调用线程的interrupt 的status

public static boolean interrupted()

该方法可以判断是否被打断,但是这个interrupt的status会被清除,

/**
     * 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 boolean isInterrupted()

该方法可以判断是否被打断

到此这篇关于Java线程中的interrupt方法解读的文章就介绍到这了,更多相关interrupt方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java 数据结构与算法系列精讲之二叉堆

    Java 数据结构与算法系列精讲之二叉堆

    二叉堆是一种特殊的堆,其实质是完全二叉树。二叉堆有两种:最大堆和最小堆。最大堆是指父节点键值总是大于或等于任何一个子节点的键值。而最小堆恰恰相反,指的是父节点键值总是小于任何一个子节点的键值
    2022-02-02
  • Java中List转Map的几种常见方式与对比

    Java中List转Map的几种常见方式与对比

    JavaList转Map是一个非常常用的技术,对于Java开发人员来讲,掌握该技术可以帮助我们更加高效地操作List集合中的对象,这篇文章主要给大家介绍了关于Java中List转Map的几种常见方式与对比的相关资料,需要的朋友可以参考下
    2024-02-02
  • Spring Boot Admin 添加报警提醒和登录验证功能的具体实现

    Spring Boot Admin 添加报警提醒和登录验证功能的具体实现

    报警提醒功能是基于邮箱实现的,当然也可以使用其他的提醒功能,如钉钉或飞书机器人提醒也是可以的,但邮箱报警功能的实现成本最低,所以本文我们就来看邮箱的报警提醒功能的具体实现
    2022-01-01
  • java datetime数据类型去掉时分秒的案例详解

    java datetime数据类型去掉时分秒的案例详解

    在Java中,如果我们想要表示一个日期而不包括时间(时分秒),我们通常会使用java.time包中的LocalDate类,这篇文章主要介绍了java datetime数据类型去掉时分秒,需要的朋友可以参考下
    2024-06-06
  • 使用RestTemplate调用https接口跳过证书验证

    使用RestTemplate调用https接口跳过证书验证

    这篇文章主要介绍了使用RestTemplate调用https接口跳过证书验证,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-10-10
  • Spring boot整合Mybatis实现级联一对多CRUD操作的完整步骤

    Spring boot整合Mybatis实现级联一对多CRUD操作的完整步骤

    这篇文章主要给大家介绍了关于Spring boot整合Mybatis实现级联一对多CRUD操作的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-07-07
  • java如何防止表单重复提交的注解@RepeatSubmit

    java如何防止表单重复提交的注解@RepeatSubmit

    @RepeatSubmit是一个自定义注解,用于防止表单重复提交,它通过AOP和拦截器模式实现,结合了线程安全和分布式环境的考虑,注解参数包括interval(间隔时间)和message(提示信息),使用时需要注意并发处理、用户体验、性能和安全性等方面,失效原因是多方面的
    2024-11-11
  • java使用Jco连接SAP过程

    java使用Jco连接SAP过程

    这篇文章主要介绍了java使用Jco连接SAP过程,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • java多线程并发中使用Lockers类将多线程共享资源锁定

    java多线程并发中使用Lockers类将多线程共享资源锁定

    Lockers在多线程编程里面一个重要的概念是锁定,如果一个资源是多个线程共享的,为了保证数据的完整性,在进行事务性操作时需要将共享资源锁定,这样可以保证在做事务性操作时只有一个线程能对资源进行操作,下面看一个示例
    2014-01-01
  • springboot返回modelandview页面的实例

    springboot返回modelandview页面的实例

    这篇文章主要介绍了springboot返回modelandview页面的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-10-10

最新评论