thread-interrupt

被打断的线程在使用sleep,join, wait方法时候都能他受到InterruptedException打断信号抛出异常

打断sleep的线程

Thread t = new Thread(() -> {
	while(true){
	
	      }
	  });
	
	  t.start();
	  try {
	      // 如果直接打断,可能还没有起来呢, 所以这里简单休眠一下
	      Thread.sleep(100);
	  } catch (InterruptedException e) {
	      e.printStackTrace();
	  }
	
	  System.out.println(t.isInterrupted());
	  // 中断
	  t.interrupt();
	  System.out.println(t.isInterrupted());

打断join的线程

这里注意:因为join的是main线程,只能打断main线程,不是打断t线程

Thread t = new Thread(() -> {
    while(true){

        }
    });

    // 打断main线程
    Thread main = Thread.currentThread();

    Thread t2 = new Thread(() -> {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 因为join的是main线程, 所以这么是打断不了t线程的, 不像sleep,wait都是blocked的当前线程
        // t.interrupt();
        
        main.interrupt();
        System.out.println("t线程被中断!");
    });

    t.start();

    t2.start();
    try {
        t.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // 不能直接在main线程中中断, 因为join的话,t线程没执行完不会执行到这里
    // t.interrupt();

打断wait的线程

public class Test {
    static final Object monitor = new Object();
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            synchronized(monitor){
                try {
                    monitor.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t.start();

        t.interrupt();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值