tryLock沒有獲得到鎖,還會繼續執行嗎?


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description:
 * @date: 2020-08-26 20:03
 * @author: yff
 */
public class TryLockTest {
    private Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        final TryLockTest test = new TryLockTest();
        for (int i = 0; i < 2; i++) {
            new Thread(() -> test.go_2(Thread.currentThread())).start();
        }
    }

    //tryLockTest_1
    public void go(Thread thread) {
        if (lock.tryLock()) {
            try {
                System.out.println(thread.getName() + "得到了鎖");
                Thread.sleep(3000);
            } catch (Exception e) {
            } finally {
                System.out.println(thread.getName() + "釋放了鎖");
                lock.unlock();
            }
        } else {
            System.out.println(thread.getName() + "獲取鎖失敗");
        }
    }

    //tryLockTest_2
    public void go_2(Thread thread) {
        boolean result = lock.tryLock();
        System.out.println(thread.getName() + "獲得鎖的結果:" + result);
        System.out.println(thread.getName() + "得到了鎖");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(thread.getName() + "釋放了鎖");
        lock.unlock();

       

    }
}

上結論:會。

 tryLock會立即返回一個結果,表明自己是否獲得了鎖,但是不管獲得與否,不會影響每個線程各自的繼續執行。
 方法go_2中,如果沒有對【獲得到鎖的結果進行區分】,那么不管是否獲得到鎖,執行的代碼都是一樣的,也沒有線程會被阻塞(與lock方法不同。
 所以,使用tryLock的時候,在得到鎖與否的后續中,一定要做好代碼區分,因為就算沒得到鎖的線程也會繼續執行與得到了鎖的線程相同的代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM