我是靠谱客的博主 畅快高跟鞋,最近开发中收集的这篇文章主要介绍interrupted()、interrupt()方法用法及注意事项,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

public class TestInterrupted {
    private static class MyThread2 extends Thread {
        @Override
        public void run() {
            //一个线程的 run() 方法执行一个无限循环,并且没有执行 sleep() 等会
            // 抛出 InterruptedException 的操作,那么调用线程的 interrupt() 方法就无法使线程提前结束
//            while (true){}

            //调用 interrupt() 方法会设置线程的中断标记,此时调用 interrupted() 方法会返回 true。
            // 因此可以在循环体中使用 interrupted() 方法来判断线程是否处于中断状态,从而提前结束线程
//            System.out.println(interrupted());//不能这样查看,一旦调用就会修改标记
            boolean a=interrupted();
            System.out.println(a);
            while (!a) {

            }
            System.out.println(Thread.currentThread().getName() + " end");
        }
    }

    private static class MyThread3 extends Thread {
        @Override
        public void run() {
            //如果该线程处于阻塞、限期等待或者无限期等待状态,那么就会抛出 InterruptedException
            try {
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName() + " run");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Thread thread2 = new MyThread2();
        thread2.start();
        thread2.interrupt();

        Thread thread3 = new MyThread3();
        thread3.start();
        thread3.interrupt();

        System.out.println("Main Thread end");
    }
}

最后

以上就是畅快高跟鞋为你收集整理的interrupted()、interrupt()方法用法及注意事项的全部内容,希望文章能够帮你解决interrupted()、interrupt()方法用法及注意事项所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(68)

评论列表共有 0 条评论

立即
投稿
返回
顶部