Home  >  Article  >  Java  >  How to use java read-write lock

How to use java read-write lock

王林
王林forward
2023-04-23 22:46:231488browse

1. Fair selectivity, supports unfair and fair lock acquisition, unfair throughput is better than fair.

2. Re-entry. Both read locks and write locks support thread re-entry.

3. Lock downgrade, follow the order of acquiring write lock, acquiring read lock, and releasing write lock. Write lock can be downgraded to read lock.

Example

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();
        }
    }
}

The above is the detailed content of How to use java read-write lock. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete