讀寫鎖:核心思想實(shí)現(xiàn)讀寫分離棉安,高并發(fā)下特別適合 讀多寫少的場景。
synchronized關(guān)鍵字和ReentrantLock 同一時(shí)間只能有一個(gè)線程進(jìn)行訪問被鎖定的代碼铸抑,讀寫鎖的機(jī)制則不是贡耽,本質(zhì)上分為兩把鎖,讀鎖和寫鎖鹊汛,在讀鎖情況下蒲赂,多個(gè)線程可以并發(fā)訪問資源,只有當(dāng)是寫鎖時(shí)只能一個(gè)一個(gè)的順序執(zhí)行柒昏。
口訣:讀讀共享凳宙,寫寫互斥,讀寫互斥职祷。
private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
private ReentrantReadWriteLock.ReadLock readLock = rwLock.readLock();
private ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock();
public void read() {
try {
readLock.lock();
System.out.println("當(dāng)前線程:" + Thread.currentThread().getName() + "進(jìn)入...");
Thread.sleep(3000);
System.out.println("當(dāng)前線程:" + Thread.currentThread().getName() + "退出...");
} catch (Exception e) {
e.printStackTrace();
} finally {
readLock.unlock();
}
}
public void write() {
try {
writeLock.lock();
System.out.println("當(dāng)前線程:" + Thread.currentThread().getName() + "進(jìn)入...");
Thread.sleep(3000);
System.out.println("當(dāng)前線程:" + Thread.currentThread().getName() + "退出...");
} catch (Exception e) {
e.printStackTrace();
} finally {
writeLock.unlock();
}
}