ReadWriteLock ReentrantReadWriteLock

时间:2022-11-30 17:31:17

ReadWriteLock管理一组锁,一个是只读的锁,一个是写锁。读锁可以在没有写锁的时候被多个线程同时持有,写锁是独占的。

所有读写锁的实现必须确保写操作对读操作的内存影响。换句话说,一个获得了读锁的线程必须能看到前一个释放的写锁所更新的内容。

读写锁比互斥锁允许对于共享数据更大程度的并发。每次只能有一个写线程,但是同时可以有多个线程并发地读数据。ReadWriteLock适用于读多写少的并发情况。

Java并发包中ReadWriteLock是一个接口,主要有两个方法,如下:

public interface ReadWriteLock {
/**
* 返回读锁
*/
Lock readLock(); /**
* 返回写锁
*/
Lock writeLock();
}

Java并发库中ReetrantReadWriteLock实现了ReadWriteLock接口并添加了可重入的特性。

实例的代码

package cn.itcast.heima2;

import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReadWriteLockTest {
public static void main(String[] args) {
final Queue3 q3 = new Queue3();
for (int i = 0; i < 3; i++) { new Thread() {
public void run() {
while (true) {
q3.get();
}
} }.start(); new Thread() {
public void run() {
while (true) {
q3.put(new Random().nextInt(10000));
}
}
}.start();
} }
} class Queue3 {
private Object data = null;//共享数据,只能有一个线程能写该数据,但可以有多个线程同时读该数据。
ReadWriteLock rwl = new ReentrantReadWriteLock(true); //true为公平锁,false则为打乱 public void get() {
rwl.readLock().lock(); //读锁上锁
try {
System.out.println(Thread.currentThread().getName() + " be ready to read data!");
Thread.sleep((long) (Math.random() * 1000));
System.out.println(Thread.currentThread().getName() + " have read data :" + data);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
rwl.readLock().unlock(); //读锁解锁
}
} public void put(Object data) { rwl.writeLock().lock(); //写锁上锁
try {
System.out.println(Thread.currentThread().getName() + " be ready to write data!");
Thread.sleep((long) (Math.random() * 1000));
this.data = data;
System.out.println(Thread.currentThread().getName() + " have write data: " + data);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
rwl.writeLock().unlock(); //写锁解锁
} }
}

结果:

Thread-0 be ready to read data!
Thread-2 be ready to read data!
Thread-4 be ready to read data!
Thread-4 have read data :null
Thread-2 have read data :null
Thread-0 have read data :null
Thread-3 be ready to write data!
Thread-3 have write data: 8786
Thread-5 be ready to write data!
Thread-5 have write data: 4237
Thread-1 be ready to write data!
Thread-1 have write data: 2771
Thread-4 be ready to read data!
Thread-2 be ready to read data!
Thread-0 be ready to read data!
Thread-2 have read data :2771
Thread-0 have read data :2771
Thread-4 have read data :2771
Thread-3 be ready to write data!
Thread-3 have write data: 4449
Thread-5 be ready to write data!