Thread ReentrantReadWriteLock

1 读写锁

2 实现。 

public class ReadWriteLockDemo {
    public static Lock lock = new ReentrantLock();
    public static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    public static Lock readLock = reentrantReadWriteLock.readLock();
    public static Lock writeLock = reentrantReadWriteLock.writeLock();
    public int value;

    public void handleRead(Lock lock) throws InterruptedException{
        try {
            lock.lock();
            Thread.sleep(1000);
            System.out.println(value);
        }finally {
            lock.unlock();
        }
    }

    public void handleWrite(Lock lock, int value) throws InterruptedException{
        try {
            lock.lock();
            Thread.sleep(1000);
            this.value = value;
        }finally {
            lock.unlock();
        }
    }
    public static void main(String[] args){
        ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo();
        Runnable read = new Runnable() {
            @Override
            public void run() {
                try {
                    readWriteLockDemo.handleRead(readLock); // 时间5秒,如果传lock重入锁 时间是20秒。
                }catch (InterruptedException e){
                }
            }
        };
        Runnable write = new Runnable() {
            @Override
            public void run() {
                try {
                    readWriteLockDemo.handleWrite(writeLock, 1);
                }catch (InterruptedException e){
                }
            }
        };

        for (int i = 0; i < 5; i++){
            new Thread(read).start();
        }
        for (int i = 18; i < 20; i++){
            new Thread(write).start();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_28197211/article/details/80931541