zoukankan      html  css  js  c++  java
  • isInterrupted()方法和interrupted()方法辨析

    注意Thread.interrupted()方法的目标对象是"当前线程",而不管本方法来自于哪个对象

    比如看如下代码:

    package threadcoreknowledge.test;
    
    public class interrupte {
    
    
    
        public static void main(String[] args) throws InterruptedException {
    
            Thread threadOne = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (; ; ) {
                    }
                }
            });
    
            // 启动线程
            threadOne.start();
            //设置中断标志
            threadOne.interrupt();
    
            //获取中断标志
            System.out.println("isInterrupted: " + threadOne.isInterrupted());
            //获取中断标志并重置
            System.out.println("isInterrupted: " + threadOne.interrupted());
    
            //获取中断标志并重直
            System.out.println("isInterrupted: " + Thread.interrupted());
            //获取中断标志
            System.out.println("isInterrupted: " + threadOne.isInterrupted());
            threadOne.join();
            System.out.println("Main thread is over.");
        }
    }
    
    

    错误的判断方法会认为输出结果是true、ture、false、false

    但是实际上第二个判断threadOne.interrupted()方法是对执行它的线程做判断,因为interrupted()方法为静态方法。执行它的线程此时是Thread主线程,因为threadOne线程已经停止了,所以第二个判断应该为false,第三个判断也为false,第四个判断为true

  • 相关阅读:
    hdu1066之数学题
    hdu1065计算几何
    hdu1060
    hdu1056
    appium安装说明
    LR安装说明
    网络编程
    读写excel
    dom
    HTML
  • 原文地址:https://www.cnblogs.com/hello-liu/p/15364764.html
Copyright © 2011-2022 走看看