其他分享
首页 > 其他分享> > isInterrupted()方法和interrupted()方法辨析

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

标签:threadOne,Thread,辨析,System,interrupted,isInterrupted,out
来源: https://www.cnblogs.com/hello-liu/p/15364764.html