zoukankan      html  css  js  c++  java
  • Java 学习笔记之 线程interrupted方法

    线程interrupted方法:

    interrupted()是Thread类的方法,用来测试当前线程是否已经中断。

    public class InterruptThread extends Thread{
        @Override
        public void run() {
            for (int i = 0; i< 5000000; i++){
                System.out.println("i=" + (i + 1));
            }
        }
    }
    
    public class ThreadRunMain {
        public static void main(String[] args) {
            testInterruptThread();
        }
    
        public static void testInterruptThread(){
            try {
                InterruptThread it = new InterruptThread();
                it.start();
                Thread.sleep(1000);
                it.interrupt();
                System.out.println("First call: " + Thread.interrupted());
                System.out.println("Second call: " + Thread.interrupted());
            } catch (InterruptedException e) {
                System.out.println("Main catch");
                e.printStackTrace();
            }
            System.out.println("end!");
        }
    }

    运行结果:

    从控制台打印的结果来看,返回的结果是false,因为当前线程是main,被中断的却是InterruptThread,所以main线程不受影响。 

    再看一个例子:

    public class ThreadRunMain {
        public static void main(String[] args) {
            testMainInterruptThread();
        }
    
        public static void testMainInterruptThread(){
            Thread.currentThread().interrupt();
            System.out.println("First call: " + Thread.interrupted());
            System.out.println("Second call: " + Thread.interrupted());
            System.out.println("end!");
        }
    }

    运行结果:

    同样是调用Thread.interrupted(), 但是为什么第一次结果是true,第二次确是false呢?

    因为interrupted()方法具有清除状态功能,所以第二次调用interrupted()返回的值是false。

  • 相关阅读:
    正则表达式(常用正则总结)
    What is maven?
    二维数组的遍历使用foreach
    Installing Git
    Hive修改表名,列名,列注释,表注释,增加列,调整列顺序,属性名等操作
    有趣的开源项目集结完毕,HelloGitHub 月刊第 63 期发布啦!
    - zxvf
    tensorflow入门
    Postman v8.7.0
    springboot等javaweb项目将jar包安装(打包)到本地Maven仓库
  • 原文地址:https://www.cnblogs.com/AK47Sonic/p/7668045.html
Copyright © 2011-2022 走看看