java synchronized加載加鎖-線程可重入
實例代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public class ReGetLock implements Runnable { @Override public void run() { get(); } public synchronized void get() { System.out.println(Thread.currentThread().getId()); set(); } public synchronized void set() { System.out.println(Thread.currentThread().getId()); } public static void main(String[] args) { ReGetLock rgl = new ReGetLock(); new Thread(rgl).start(); } } |
執(zhí)行代碼的線程到底能不能進(jìn)入到set方法呢?
因為線程rgl先調(diào)用了get方法,獲取到了ReGetLock對象的鎖,那么當(dāng)線程rgl想進(jìn)入標(biāo)有synchronized 關(guān)鍵字的set方法時,會被阻塞住,一直等待嗎?
其實是不會的,在JAVA里面,當(dāng)某個線程試圖獲得一個已經(jīng)由它自己持有的鎖,那么這個請求會成功。不然會出現(xiàn)死鎖。
因此像synchronized 這種加鎖機(jī)制,線程是可重入的。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/linsongbin1/article/details/55188478