首页 > 文章列表 > java interrupt()打断阻塞的操作

java interrupt()打断阻塞的操作

java interrupt
444 2022-08-06

说明

1、调用interrupt()可以打断阻塞,打断阻塞并不等于线程的生命周期结束,仅仅是打断了当前线程的阻塞状态。

2、一旦在阻塞状态下被打断,就会抛出一个InterruptedException的异常,这个异常就像一个信号一样通知当前线程被打断了。

实例

public static void main(String[] args) throws InterruptedException{
    Thread thread = new Thread(()->{
        try{
            TimeUnit.SECONDS.sleep(10);
        }catch (InterruptedException e){
            System.out.println("Thread is interrupted.");
        }
    });
    thread.start();
    TimeUnit.SECONDS.sleep(1);
    thread.interrupt();
}

本教程操作环境:windows7系统、java10版,DELL G3电脑。