前言
读读共享
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();
}