java.util.concurrent.locks.Lock類的lock和lockInterruptibly方法的區別__lock和lockInterruptib

來源:互聯網
上載者:User

什麼是可中斷的鎖擷取呢。就是:線程在等待擷取鎖的過程中,是否能夠響應中斷,以便在被中斷的時候能夠解除阻

塞狀態,而不是傻傻地一直在等待。java對象的內建鎖(synchronized)就是一種不可中斷的鎖,也就是說如果一個線

程在等待擷取某個對象的內建鎖,就算是該線程被其他線程中斷,該線程仍然繼續等待內建鎖,而不是解除阻塞狀

態,也不會拋出InterruptedException。Lock類的lock()類似synchronized,是不可中斷的,在等待擷取鎖的過程中,

不響應插斷要求;lockInterruptibly是可中斷的,線程在等待擷取鎖的過程中,能夠響應中斷並拋出異常。

public static void testLock() throws Exception{    final Lock lock = new ReentrantLock();    Thread t1 = new Thread(new Runnable()    {        @Override        public void run()        {            // 1.測試lock            // lock.lock();            // 2.測試lockInterruptibly            try            {                lock.lockInterruptibly();            }            catch (InterruptedException e)            {                System.out.println(" interrupted.");            }        }    });    // 佔用鎖的時候,讓t1開始運行    lock.lock();    t1.start();    Thread.sleep(100);    t1.interrupt();}

可以分別注釋1和2處的代碼,進行測試。調用lock.lock()發現線程t1一直不能結束,即t1一直在等待擷取鎖;調用lock.

lockInterruptibly()發現t1線程能夠終止,並列印interrupted,即響應了線程插斷要求。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.