天天看點

LockSupport無故放開鎖的問題

本文為筆者在學習過程中遇到的未解決的問題,請各位大牛幫忙在評論區或聯系筆者解答

代碼如下,問題見注釋

/**
     * 全程沒有LockSupport.unpark()代碼,但是控制台列印出了over字段
     * LockSupport.park()線上程中并且之前有線程被中斷時無法加鎖
     *
     * 環境:jdk1.8,windows8
     */
    private void testPermitBug() {
        Thread thread1 = new Thread(()->{
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                System.out.println("睡眠被中斷");
            }
        });
        thread1.start();
        waitAMoment();
        thread1.interrupt();

        Thread thread2 = new Thread(()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            LockSupport.park();
            System.out.println("over");
        });
        thread2.start();
        waitAMoment();
        printThreadState(thread2);
    }
           

運作結果

LockSupport無故放開鎖的問題

個人見解

在jdk源碼LockSupport.java的第160行發現了這一句

這是park()方法的注釋,說這個方法可能會無條件結束。。。不是吧

Github部落格