并发编程之 ReentrantReadWriteLock
ReentrantReadWriteLock 基本用法
java
package com.mengweijin.learning.basic.lock;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 读写锁
*
* @author mengweijin
*/
public class ReentrantReadWriteLockTest {
static ReentrantReadWriteLock rrwl = new ReentrantReadWriteLock();
static ReentrantReadWriteLock.ReadLock r = rrwl.readLock();
static ReentrantReadWriteLock.WriteLock w = rrwl.writeLock();
public static void main(String[] args) {
// readWriteLock();
// doubleWriteLock();
doubleReadLock();
}
/**
* 读写互斥
* 先打印完 t1,再打印 t2
*/
public static void readWriteLock() {
new Thread(new Printer(r), "t1-read").start();
new Thread(new Printer(w), "t2-read").start();
}
/**
* 写写互斥
* 先打印完 t1,再打印 t2
*/
public static void doubleWriteLock() {
new Thread(new Printer(w), "t1-read").start();
new Thread(new Printer(w), "t2-read").start();
}
/**
* 读读并发
* t1,t2 并发执行,交替打印,谁拿到 CPU 执行权,谁就打印。
*/
public static void doubleReadLock() {
new Thread(new Printer(r), "t1-read").start();
new Thread(new Printer(r), "t2-read").start();
}
static class Printer implements Runnable {
private Lock lock;
public Printer(Lock lock) {
this.lock = lock;
}
@Override
public void run() {
lock.lock();
try {
for (int i = 0; i < 5; i++) {
print(i);
}
} finally {
lock.unlock();
}
}
private void print(int i) {
try {
System.out.println(Thread.currentThread().getName() + ":" + i);
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}