栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

线程的中断

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

线程的中断

线程的中断
    • 中断线程
      • 执行完毕
      • 修改判定标记
      • 在catch中添加break
            • 补充

中断线程

要中断一个线程
1、让线程的入口方法执行完毕
2、使用Thread类提供的interrupt方法(如:把while中的判定标记改成基于Thread.currentThread().isInterrupted(),或者在catch里添加break,)

执行完毕
public class Demo05 {
    static boolean isQuit = true ;
    public static void main(String[] args) {
        Thread t = new Thread(){
            @Override
            public void run() {
                while (isQuit == true){
                    System.out.println("新线程");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        t.start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("让线程中断");
        isQuit = false;
    }
}
修改判定标记
public class Demo06 {
    public static void main(String[] args) {
        Thread t = new Thread(){
            @Override
            public void run() {
                while (!Thread.currentThread().isInterrupted()){//判断当前线程是否中断
                    System.out.println("新线程");
                }
            }
        };
        t.start();
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t.interrupt();
        System.out.println("让线程中断");
    }
}
在catch中添加break
public class Demo07 {
    public static void main(String[] args) {
        Thread t = new Thread(){
            @Override
            public void run() {
                while (true){//判断当前线程是否中断
                    System.out.println("新线程");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        break;
                    }
                }
            }
        };
        t.start();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t.interrupt();
        System.out.println("让线程中断");
    }
}
补充

调用interrupt方法时,可能会有两种情况
1、此时线程正处于休眠状态,那么此时直接出现休眠异常被catch到,执行catch中的代码,此时就可以在catch中添加break
2、线程没有处于休眠状态,那么此时就继续执行,这样就可以通过标志位Thread.currentThread().isInterrupted()来进行中断线程,如果有休眠状态则会休眠状态异常从而继续线程。

调用interrupt时,不一定就可以中断异常!!,具体还是要看代码逻辑


.如果线程没有调用 wait/join/sleep 等方法,interrupt()时,就会改变
Thread.currentThread()isInterrupted()的值,但不会改变Thread.interrupted() 的值
Thread.interrupted() 就相当于一个可以自动反弹的按钮,按下去就自动反弹上来(清楚标记)
Thread.currentThread()isInterrupted()就像一个普通按钮,按下去不会反弹

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/683543.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号