前言
读读共享
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 {
lock.readLock().unlock();
}
}).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 {
lock.writeLock().unlock();
}
}).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 {
lock.writeLock().unlock();
}
}).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 {
lock.readLock().unlock();
}
}).start();
} 参考博客
本文标题:ReentrantReadWriteLock实现原理
本文链接:https://blog.quwenai.cn/post/8501.html
版权声明:本文不使用任何协议授权,您可以任何形式自由转载或使用。






还没有评论,来说两句吧...