• 多线程 interrupt()方法


    java interrupt()方法只是设置线程的中断标记,当对处于阻塞状态的线程调用interrupt方法时(处于阻塞状态的线程是调用sleep, wait, join 的线程),会抛出InterruptException异常,而这个异常会清除中断标记。并且异常如果被捕获且没有重新抛出后续代码将继续执行。Thread.interrupt()方法不会中断一个正在运行的线程。这一方法实际上完成的是,在线程受到阻塞时抛出一个中断信号,这样线程就得以退出阻塞的状态。更确切的说,如果线程被Object.wait, Thread.join和Thread.sleep三种方法之一阻塞,那么,它将接收到一个中断异常(InterruptedException),从而提早地终结被阻塞状态。 

    代码如下:

    public class Main {
    @Test
    public void interruptedTest() {

    Runnable runnableError = () -> {
    //不会退出
    while (!Thread.interrupted()) {
    System.out.println(new Date());
    try {
    TimeUnit.SECONDS.sleep(3);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    //unreachable
    System.out.println("interrupted: " + Thread.interrupted());
    };
    //可以退出
    Runnable runnable = () -> {
    try {
    while (!Thread.interrupted()) {
    System.out.println(new Date());
    TimeUnit.SECONDS.sleep(3);
    }
    //unreachable
    System.out.println("interrupted: " + Thread.interrupted());
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    System.out.println("reachable");
    };
    Thread thread = new Thread(runnable);

    thread.start();
    try {
    TimeUnit.SECONDS.sleep(2);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    thread.interrupt();
    try {
    thread.join();
    Thread.sleep(5000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    assert (!thread.isInterrupted());
    System.out.println("end: " + new Date());
    }
    }

    特别需要注意的是:

    Thread.Interrupted()除了会返回当前线程是否被中断之外,还会将线程状态恢复为未中断状态。而public boolean isInterrupted()不改变状态


    代码如下:
        //清除状态
        public static boolean interrupted() {
            return currentThread().isInterrupted(true);
        }
        //保留状态
        public boolean isInterrupted() {
            return isInterrupted(false);
        }
    

      

    参考:

    http://blog.csdn.net/u013238950/article/details/53893676

    http://blog.csdn.net/wxwzy738/article/details/8516253

  • 相关阅读:
    Python--文件操作
    Python--数据类型整理
    u-boot之NAND启动与NOR启动的区别
    u-boot之make all执行过程分析
    编译过程和符号表重定位问题、静态和动态链接
    u-boot之make <board_name>_config执行过程分析
    u-boot之ARM920T的start.S分析
    在使用Myeclipse时,用Tomcat添加部署项目的时候报错,或启动tomcat报错
    关于JDK,tomcat,eclipse的配置
    我的博客
  • 原文地址:https://www.cnblogs.com/heapStark/p/8167747.html
Copyright © 2020-2023  润新知