interrupt、isInterrupted 、interrupted

192 阅读1分钟

参考文章: interrupt、isInterrupted 、interrupted

public class ThreadTest {


    public static void main(String[] args) throws Exception{

        Object A = new Object();

        Thread t1 = new Thread() {
            @Override
            public void run() {
                synchronized (A) {
                    System.out.println("t1 线程获取到锁资源,阻塞 10 s");
                    long start = System.currentTimeMillis();
                    try {
//                        A.wait();
                        Thread.sleep(10000);

                    } catch (InterruptedException e) {
                        //wait、join、sleep引发线程阻塞后,外部线程调用t1.interrupt()会将 终止状态 置为 true,
                        // 线程会立即从阻塞状态被唤起,并抛出 InturruptedException,同时将终止状态置回 false
                        System.out.println("结束休眠,抛出InterruptedException,休眠时间:" + (System.currentTimeMillis() - start) + "ms");
                    } catch (Exception e){
                        System.out.println("====="+e.getMessage());
                    }
                }
            }
        };
        t1.start();

        Thread.sleep(3000);
        System.out.println("interrupt t1");
        t1.interrupt();

    }
}

image.png