使用示例
public class Test {
private ReadWriteLock rwLock = new ReentrantReadWriteLock();
//写锁
public void write() {
rwLock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName()+":写开始!");
TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName()+":写结束!");
} catch (Exception e) {
e.printStackTrace();
} finally {
rwLock.writeLock().unlock();
}
}
//读锁
public void read() {
rwLock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName()+":读开始!");
TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName()+":读结束!");
} catch (Exception e) {
e.printStackTrace();
} finally {
rwLock.readLock().unlock();
}
}
public static void main(String[] args) throws Exception{
Test test = new Test();
for(int i=1; i<=3; i++) {
new Thread(() -> {
test.write();
}, "Thread-"+i).start();
}
for(int i=4; i<=6; i++) {
new Thread(() -> {
test.read();
}, "Thread-"+i).start();
}
}
}
结果:
Thread-1:写开始!
Thread-1:写结束!
Thread-2:写开始!
Thread-2:写结束!
Thread-3:写开始!
Thread-3:写结束!
Thread-4:读开始!
Thread-5:读开始!
Thread-6:读开始!
Thread-4:读结束!
Thread-5:读结束!
Thread-6:读结束!