欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

聊聊Java 中的线程中断

时间:2021-04-29 10:56:07|栏目:JAVA代码|点击:

Java如何实现线程中断?

通过调用Thread类的实例方法interrupt。如下:

Thread thread = new Thread(){
      @Override
      public void run() {
        if(isInterrupted()){
          System.out.println("interrupt");
        }
      }
    };
    thread.start();

    thread.interrupt();

线程中断后线程会立即停止执行吗?

NO。 而如果线程未阻塞,或未关心中断状态,则线程会正常执行,不会被打断。

Thread.interrupt()的官方解释是这样的:

If this thread is blocked in an invocation of the

Object#wait() wait(), { Object#wait(long) wait(long)}, or { Object#wait(long, int) wait(long, int)} methods of the { Object} class, or of the { #join()}, { #join(long)}, { #join(long, int)}, { #sleep(long)}, or { #sleep(long, int)}, methods of this class, then its interrupt status will be cleared and it will receive an { InterruptedException}.

也就是:处于阻塞的线程,即在执行Object对象的wait()、wait(long)、wait(long, int),或者线程类的join()、join(long)、join(long, int)、sleep(long)、sleep(long,int)方法后线程的状态,当线程调用interrupt()方法后,这些方法将抛出InterruptedException异常,并清空线程的中断状态。

比如下面的例子会中断两次,第一次sleep方法收到中断信号后抛出了InterruptedException,捕获异常后中断状态清空,然后继续执行下一次:

public static void main(String[] args) throws InterruptedException {
    Thread thread = new Thread(){
      @Override
      public void run() {
        try {
          Thread.sleep(10000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }

        System.out.println("interrupt");

        try {
          Thread.sleep(10000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    };
    thread.start();

    thread.interrupt();
    Thread.sleep(5000);
    thread.interrupt();
  }

而下面这个例子则会一直执行,不会被打断:

public static void main(String[] args) throws InterruptedException {
    Thread thread = new Thread(){
      @Override
      public void run() {
        while (true)
        System.out.println("interrupt");
      }
    };
    thread.start();

    thread.interrupt();
  }

interrupted与isInterrupted方法啥区别?

  • Thread类的静态方法interrupted:测试当前线程是否已经中断。如果线程处于中断状态返回true,否则返回false。同时该方法将清除的线程的中断状态。即:如果连续两次调用该方法,则第二次调用将返回false。该方法可用于清除线程中断状态使用。
  • Thread类的实例方法isInterrupted:测试线程是否已经中断。线程的中断状态不受该方法的影响。

Thread类并没有提供单独清除中断状态的方法,所以有两种方式来达到此目的:

  • 对于sleep等阻塞方法,catch InterruptedException异常;
  • 调用Thread类的静态方法interrupted

线程中断有哪些实际应用?

线程中断的几个实际应用场景:

  • 在处理Web请求时,可能将请求分配到多个线程去处理,实现请求执行的超时机制;
  • 实现线程池时,关闭线程池中的线程任务。

上一篇:Java反转字符串和相关字符编码的问题解决

栏    目:JAVA代码

下一篇:mybatis教程之查询缓存(一级缓存二级缓存和整合ehcache)

本文标题:聊聊Java 中的线程中断

本文地址:http://www.codeinn.net/misctech/111035.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有