线程中断

当一个线程处于阻塞状态时,需要提供一种唤醒机制。例:

 1    public static void main(String[] args) {
 2         Thread t = new Thread(() -> {
 3             try {
 4                 Thread.sleep(5000);
 5             } catch (InterruptedException e) {
 6                 System.out.println(Thread.currentThread().isInterrupted());
 7             }
 8         });
 9 
10         t.start();
11         t.interrupt();
12     }

子线程 t 在执行的过程中睡着了,主线程等不及了,提醒子线程(设置子线程的中断标志),sleep这个动作可以响应中断,清除中断状态,然后抛出异常(下方模拟实现)。打印出来的中断标志是false。

public void throwInterruptedException() throws InterruptedException{
    if (Thread.interrupted()) //获取中断状态后,会重新复原
            throw new InterruptedException();
}

怎么处理捕获到的中断异常呢?

1. 抛到上层

2. 重设线程的中断标志,交由上层判断

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                skating();
            }
            System.out.println("开始干活");
        });

        t.start();

        Thread.sleep(500);
        t.interrupt();

    }

    private static void skating() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            System.out.println("被发现了:_(");
            Thread.currentThread().interrupt();
        }
    }

 

posted @ 2021-01-25 15:28  walker993  阅读(99)  评论(0编辑  收藏  举报