0
点赞
收藏
分享

微信扫一扫

ReentrantReadWriteLock实现原理

小典典Rikako 2022-08-04 阅读 58


前言

读读共享

public static void main(String[] args) {

ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

/*
* 1525541261947 Thread-0 获得读锁
* 1525541261947 Thread-2 获得读锁
* 1525541261947 Thread-1 获得读锁
*/

for (int i = 0; i < 3; i++) {
new Thread(() -> {
lock.readLock().lock();
try {
System.out.println(System.currentTimeMillis() + " " + Thread.currentThread().getName() + " 获得读锁");
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
} finally.start();
}
}

写写互斥

public static void main(String[] args) {

ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

/*
* 1525541686021 Thread-0 获得写锁
* 1525541687023 Thread-2 获得写锁
* 1525541688023 Thread-1 获得写锁
*/

for (int i = 0; i < 3; i++) {
new Thread(() -> {
lock.writeLock().lock();
try {
System.out.println(System.currentTimeMillis() + " " + Thread.currentThread().getName() + " 获得写锁");
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
} finally.start();
}
}

读写互斥

public static void main(String[] args) {

ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

/*
* 1525541885280 Thread-0 获得写锁
* 1525541886282 Thread-1 获得读锁
*/

new Thread(() -> {
lock.writeLock().lock();
try {
System.out.println(System.currentTimeMillis() + " " + Thread.currentThread().getName() + " 获得写锁");
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
} finally.start();

new Thread(() -> {
lock.readLock().lock();
try {
System.out.println(System.currentTimeMillis() + " " + Thread.currentThread().getName() + " 获得读锁");
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
} finally.start();
}

参考博客


举报

相关推荐

0 条评论