线程停止

1.使用API

isInterrupted():判断当前线程是否停止,false表示没有停止,true表示停止
interrupt():标记线程停止,只是打了标记不是强制停止线程
interrupted():静态方法调用会将标记状态设置为false,

public class MyInterrupt implements Runnable {
    @Override
    public void run() {
        Thread thread = Thread.currentThread();
        // 判断当前线程标记状态
        while(!thread.isInterrupted()){
            System.out.println("线程执行中");
        }
        System.out.println("线程执行完毕");
    }

    public static void main(String[] args) throws InterruptedException {
        MyInterrupt interrupt = new MyInterrupt();
        Thread thread = new Thread(interrupt);
        thread.start();
        Thread.sleep(1);
        // 线程停止标记
        thread.interrupt();

    }
}

抛出InterruptedException异常会重置中断标记

	package com.cairenhui;

/**

  • 实现线程中断方式

*/

public class Interrupt implements Runnable{


    @Override
    public void run() {
        while(!Thread.currentThread().isInterrupted()){
            try {
                Thread t = Thread.currentThread();
                System.out.println("hhhhhhhh");
                Thread.sleep(200);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(Thread.currentThread().isInterrupted());
                // 停止线程
                Thread.currentThread().interrupt();
            }
        }



    }

    public static void main(String[] args) throws InterruptedException {
        Interrupt t = new Interrupt();
        Thread thread = new Thread(t);
        thread.start();
        Thread.sleep(100);
        thread.interrupt();
    }
}

在这里插入图片描述
线程睡眠的时候停止线程抛出InterruptedException异常会将中断标志置为false,可以
Thread.currentThread().interrupt();重置标记

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值