JUC的ReadWriteLock示例

ReadWriteLock 可以实现的是可以多线程读,然后写线程不与读线程冲突

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class TestReadWriteLock {
     static Lock lock = new ReentrantLock();// 这里引入ReentrantLock()是为了比较读锁和写锁的区别,ReentrantLock()读写都排队获取

     static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
     static Lock readLock = readWriteLock.readLock();//属于共享锁
     static Lock writeLock = readWriteLock.writeLock();//属于排他锁

     public static void read(Lock lock){
         try{
             lock.lock();
             Thread.sleep(1000);
             System.out.println("read is over!");
         }catch (InterruptedException e){
             e.printStackTrace();
         }finally {
             lock.unlock();
         }
     }

     public static void write(Lock lock){
         try {
             lock.lock();
             Thread.sleep(1000);
             System.out.println("write is over!");
         } catch (Exception e) {
             e.printStackTrace();
         } finally {
             lock.unlock();
         }
     }

    public static void main(String[] args) {
//        Runnable readR = ()->read(lock);
//        Runnable writeR = ()->write(lock,new Random().nextInt());

        Runnable readR = ()->read(readLock);
        Runnable writeR = ()->write(writeLock);

        for (int i = 0; i <10 ; i++) {
            new Thread(readR).start();
        }

        for (int i = 0; i < 2; i++) {
            new Thread(writeR).start();
        }
    }

}

输出结果:

read is over!
read is over!
read is over!
read is over!
read is over!
read is over!
read is over!
read is over!
read is over!
read is over!  //这10个读是一瞬间完成的
write is over!
write is over!

当然为了对比,采用另一个锁,放开这段注释

//        Runnable readR = ()->read(lock);
//        Runnable writeR = ()->write(lock,new Random().nextInt());

输出结果如下:

read is over!
read is over!
read is over!
read is over!
read is over!
read is over!
read is over!
read is over!
read is over!
read is over! //这10个读是1秒输出打印一次“write is over”
write is over!
write is over!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值