ReentrantReadWriteLock读写锁
- 通过lock.readLock().lock 调用读锁,lock.writeLock().lock调用写锁
- 读锁之间共享锁
- 写锁之间互斥
- 读写锁之间互斥
例子:
import java.util.concurrent.locks.ReentrantReadWriteLock;
class MyService06 {
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public void read() {
try {
lock.readLock().lock();
System.out.println(Thread.currentThread().getName() + "获得读锁" + System.currentTimeMillis());
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.readLock().unlock();
}
}
public void write() {
try {
lock.writeLock().lock();
System.out.println(" " + Thread.currentThread().getName() + "获得写锁" + System.currentTimeMillis());
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.writeLock().unlock();
}
}
}
public class StudyThreads06读写锁 {
public static void main(String[] args) {
MyService06 myService06 = new MyService06();
// 读锁不互斥
for (int i = 0; i < 10; i++) {
Thread thread1 = new Thread(() -> {
myService06.read();
});
thread1.start();
}
// 写锁互斥
for (int i = 0; i < 10; i++) {
Thread threadWrite = new Thread(() -> myService06.write());
threadWrite.start();
}
// 读写互斥
for (int i = 0; i < 5; i++) {
Thread threadRead1 = new Thread(()->myService06.read());
Thread threadWrite2 = new Thread(()->myService06.write());
threadRead1.start();
threadWrite2.start();
}
}
}