Appearance
12_读锁和写锁
- 读锁又叫共享锁,写锁又叫排他锁/独占锁。
- 读锁和写锁都会发生死锁
- 读锁和写锁是为了解决多线程读写问题的一种锁机制.
ReadWriteLock
- 读写锁是一种读写分离锁,读读共享,读写互斥,写写互斥。
- 读写锁的实现类ReentrantReadWriteLock,内部有两个锁,一个读锁,一个写锁。
- ReentrantReadWriteLock的使用示例:
java
public class ReadWriteLockDemo {
private int count = 0;
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public void increment() {
lock.writeLock().lock();
try {
count++;
} finally {
lock.writeLock().unlock();
}
}
public int getCount() {
lock.readLock().lock();
try {
return count;
} finally {
lock.readLock().unlock();
}
}
public static void main(String[] args) throws InterruptedException {
ReadWriteLockDemo counter = new ReadWriteLockDemo();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("Final count: " + counter.getCount());
}
}