Java 学习笔记之 线程isInterrupted方法

Posted AK47Sonic

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 学习笔记之 线程isInterrupted方法相关的知识,希望对你有一定的参考价值。

线程isInterrupted方法:

 

isInterrupted()是Thread对象的方法,测试线程是否已经中断。

public class ThreadRunMain {
    public static void main(String[] args) {
        testMainIsInterruptThread();
    }

    public static void testMainIsInterruptThread(){
        Thread.currentThread().interrupt();
        System.out.println("First call: " + Thread.currentThread().isInterrupted());
        System.out.println("Second call: " + Thread.currentThread().isInterrupted());
        System.out.println("end!");
    }
}

运行结果:

public class IsInterruptThread  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) {
        testIsInterruptThread();
    }


    public static void testIsInterruptThread(){
        try {
            IsInterruptThread iit = new IsInterruptThread();
            iit.start();
            Thread.sleep(1000);
            iit.interrupt();
            System.out.println("First call: " + iit.isInterrupted());
            System.out.println("Second call: " + iit.isInterrupted());
        } catch (InterruptedException e) {
            System.out.println("Main catch");
            e.printStackTrace();
        }
        System.out.println("end!");
    }
}

运行结果:

 

以上是关于Java 学习笔记之 线程isInterrupted方法的主要内容,如果未能解决你的问题,请参考以下文章

关于Java多线程-interrupt()interrupted()isInterrupted()解释

java---interruptinterrupted和isInterrupted的区别

java多线程 interrupt(), interrupted(), isInterrupted()方法区别

Java 中 interrupted 和 isInterrupted 方法的区别?

Java 中 interrupted 和 isInterrupted 方法的区别?

java 多线程5: java 终止线程及中断机制 (stop()interrupt() interrupted()isInterrupted())