Java 多執行緒高併發 3.5 — ReadWriteLock 讀寫鎖使用
ReadWriteLock 又稱為共享鎖,的讀寫分離鎖,內部分為讀鎖和寫鎖
關於 A 和 B 執行緒,讀和寫的關係
A 讀 — B 讀:不互斥、不阻塞 A 讀 — B 寫:互斥,互相阻塞 A 寫 — B 寫:互斥,互相阻塞
用法:非常簡單,和 ReentrantLock 一樣
public class TestReadWriteLock {
// 例項化讀寫鎖
private static final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private static final Lock readLock = readWriteLock.readLock();
private static final Lock writeLock = readWriteLock.writeLock();
private static int count = 0;
static class ReadThread implements Runnable {
@Override
public void run() {
readLock.lock();
try {
System.out.println(System.currentTimeMillis() + " : " + Thread. currentThread().getName() + " 進來了: count = " + count);
Thread.sleep(2000);
} catch (Exception e) {
} finally {
readLock.unlock();
}
}
}
static class WriteThread implements Runnable {
@Override
public void run() {
writeLock.lock();
try {
System.out.println(System.currentTimeMillis () + " : " + Thread.currentThread().getName() + " 進來了: count = " + (++count));
Thread.sleep(2000);
} catch (Exception e) {
} finally {
writeLock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
System.out.println("======開始測試寫鎖======");
Thread[] threads = new Thread[10];
ReadThread read = new ReadThread();
for (int i = 0; i < threads.length; i++) threads[i] = new Thread(read, "執行緒 " + i);
for (int i = 0; i < threads.length; i++) threads[i].start();
for (int i = 0; i < threads.length; i++) threads[i].join();
System.out.println("\n======開始測試讀鎖======");
WriteThread write = new WriteThread();
for (int i = 0; i < threads.length; i++) threads[i] = new Thread(write, "執行緒 " + i);
for (int i = 0; i < threads.length; i++) threads[i].start();
for (int i = 0; i < threads.length; i++) threads[i].join();
}
}
輸出結果,讀鎖相當於沒有鎖 ======開始測試寫鎖====== 1537876265912 : 執行緒 0 進來了: count = 0 1537876265912 : 執行緒 1 進來了: count = 0 1537876265912 : 執行緒 2 進來了: count = 0 1537876265912 : 執行緒 3 進來了: count = 0 1537876265913 : 執行緒 5 進來了: count = 0 1537876265912 : 執行緒 4 進來了: count = 0 1537876265913 : 執行緒 7 進來了: count = 0 1537876265913 : 執行緒 8 進來了: count = 0 1537876265913 : 執行緒 6 進來了: count = 0 1537876265913 : 執行緒 9 進來了: count = 0 ======開始測試讀鎖====== 1537876267915 : 執行緒 0 進來了: count = 1 1537876269916 : 執行緒 2 進來了: count = 2 1537876271916 : 執行緒 1 進來了: count = 3 1537876273917 : 執行緒 4 進來了: count = 4 1537876275918 : 執行緒 3 進來了: count = 5 1537876277918 : 執行緒 5 進來了: count = 6 1537876279919 : 執行緒 6 進來了: count = 7 1537876281919 : 執行緒 7 進來了: count = 8 1537876283920 : 執行緒 8 進來了: count = 9 1537876285920 : 執行緒 9 進來了: count = 10