并发编程之读写锁设计模式(ReadWriteLock design pattern or Reader-Writer design pattern)

在进行读写操作的时候,读是可以并发的,但是写是不可以的,只能串行

 READERWRITER
READERYESNO
WRITERNONO

这种方式是把读操作放开,提高线程执行速度,把写操作添加同步代码块,保证顺序性原子性。

 

public class ReadWriteLock {

    private int readings = 0;
    private int waitingReaders = 0;
    private int writings = 0;
    private int waitWriters = 0;
    private boolean preform;

    public ReadWriteLock() {
        this(true);
    }

    public ReadWriteLock(boolean preform) {
        this.preform = preform;
    }

    public synchronized void readLock() throws InterruptedException {
        waitingReaders++;
        try {
            while (writings > 0 && (preform && waitWriters > 1)) {
                this.wait();
            }
            readings++;
        } finally {
            waitingReaders--;
        }
    }

    public synchronized void readUnlock() {
        notifyAll();
        readings--;
    }

    public synchronized void writeLock() throws InterruptedException {
        waitWriters++;
        try {
            while (writings > 0 || readings > 0) {//如果是正在写或者正在读,就不可以进行写的操作
                wait();
            }
            writings++;
        } finally {
            waitWriters--;
        }
    }

    public synchronized void writeUnlock() {
        notifyAll();
        writings--;
    }

}

public class SharedResource {
    private final ReadWriteLock lock = new ReadWriteLock();
    private final char[] buffer ;
    public SharedResource(int size){
        buffer = new char[size];
        for(int i = 0 ; i < size ; i++){
            buffer[i] = '*';

        }
    }

    public char[] read() throws InterruptedException{
        try {
            lock.readLock();
            return doRead();
        } finally {
            lock.readUnlock();
        }
    }

    private char[] doRead() {
        char[] bufferCopy = new char[buffer.length];
        for(int i = 0 ,length = buffer.length; i < length; i++){
            bufferCopy[i] = buffer[i];
        }
        return bufferCopy;
    }

    public void write(char c) throws InterruptedException {
        try {
            lock.writeLock();
            doWrite(c);
        }finally {
            lock.writeUnlock();
        }
    }

    private void doWrite(char c) {
        for(int i = 0 ,length = buffer.length; i < length ; i ++){
            buffer[i] = c;
        }
        System.out.println(Thread.currentThread().getName() + " write " + String.valueOf(buffer));
    }
    
    public class Reader extends Thread {

    private SharedResource resource;

    public Reader(SharedResource resource) {
        this.resource = resource;
    }

    @Override
    public void run() {
        try {
            while (true) {
                System.out.println(getName() + " read " + String.valueOf(resource.read()));
                Thread.sleep(45);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class Writer extends Thread {

    private SharedResource resource;
    private String filler;
    private Random random = new Random(System.currentTimeMillis());

    public Writer(SharedResource resource, String filler) {
        this.resource = resource;
        this.filler = filler;
    }

    @Override
    public void run() {
        try {
            while (true) {
                resource.write(nextChar());
                Thread.sleep(50);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private char nextChar() {
        int index = random.nextInt(filler.length());
        return filler.charAt(index);
    }
}

public class ReaderWriterClient {

    public static void main(String[] args){
        SharedResource r = new SharedResource(10);
        new Reader(r).start();
        new Reader(r).start();
        new Reader(r).start();
        new Reader(r).start();
        new Reader(r).start();
        new Writer(r,"qwertyuiopasdf").start();
        new Writer(r,"QWERTYUIOPASDF").start();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值