线程的中断标志位

interrupt()打断每个线程(设置标志位)
isInterrupted()查询某个线程是否被打断过(查询标志位)
static interrupted()查询当前线程是否被打断过,并重置打断标志

当线程sleep或wait、join时,如果这时设置标志位会产生InterruptedException异常,catch后可以进行处理,标志位也会复位。
锁操作不会被Interrupte()干扰
lockInterruptibly()可以干扰,使其抛出异常,catch异常后可以进行自定义操作。

面试题:怎么优雅的结束一个线程
不建议使用stop()方法。容易产生数据不一致的问题,stop方法太粗暴了。suspend和resume方法也是同样的。
1、设置标志位结束线程

 for (;;){
                if (Thread.currentThread().isInterrupted()) {
                    break;//设置过标志位就结束线程
                }
            }

2、使用volatile 变量(不依赖中间状态时使用)

    private static volatile boolean running =true;
    public static void main(String[] args) {

        Thread t = new Thread(()-> {
            while (running){
                System.out.println("a");
            }
        });
        t.start();
        
        running=false;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值