并发编程-基础篇(七)-线程中断

interrupt():中断线程
isInterrupted():是否中断线程,如果是返回true,不是返回false
Thread.interrupted():是否中断线程,如果是返回true,不是返回false,不同于isInterrupted()的区别是,他会清除中断标记
  public static void main(String[] args) {

        Thread thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println(Thread.currentThread() + "hello");
            }
        });
        thread.start();
        try {
            Thread.sleep(1000);
            System.out.println("main thread interrupt thread");
            thread.interrupt();
            thread.join();
            System.out.println("main is over");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
}
// 当现在还处在sleep方法的时候,调用interrupt 会抛出InterruptedException 
    public static void main(String[] args) {


        Thread thread = new Thread(() -> {
            try {
                System.out.println("threadOne begin sleep for 2000 seconds");
                Thread.sleep(2000000);
                System.out.println("threadOne awaking");
            } catch (InterruptedException e) {
                System.out.println("threadOne is interrupted while sleeping");
                return;
            }
            System.out.println("thread-leaving normaily");
        });

        thread.start();
        try {
            // 确保子线程进入休眠状态
            Thread.sleep(2000);
            thread.interrupt();
            thread.join();
            System.out.println("main thread is over");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
}
    public static void main(String[] args) {

        Thread thread = new Thread(() -> {
        // 自旋
            for (; ; ) {
            }

        });
        // 启动线程
        thread.start();
        // 设置中断标志
        thread.interrupt();
        // 获取中断标志
        System.out.println("isInterrupt:"+thread.isInterrupted());
        // 获取中断标志并重置
        System.out.println("isInterrupt:"+Thread.interrupted());
        
        try {
            // 程序一直不会停止
            thread.join();
            System.out.println("main thread is over");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值