深入解析:Java读写锁的关键特性与实战应用
1、公平选择性,支持非公平和公平锁获取,吞吐量不公平优于公平。
2、重进入,读锁和写锁都支持线程重进入。
3、锁降级,遵循获取写锁、获取读锁、释放写锁的顺序,写锁可以降级为读锁。
实例
-
- public class ReadWriteLockTest {
- public static void main(String[] args) {
- final Queue q = new Queue();
- for (int i = 0; i < 3; i++) {
- new Thread() {
- @Override
- public void run() {
- while (true) {
- q.get();
- }
- }
- }.start();
- new Thread() {
- @Override
- public void run() {
- while (true) {
- q.put(new Random().nextInt(10000));
- }
- }
- }.start();
- }
- }
- }
- class Queue {
- ReadWriteLock rwl = new ReentrantReadWriteLock();
- private Object data = null;
- 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();
- }
- }
- }
复制代码
以上就是java读写锁的特性,希望对大家有所帮助。
|