温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java多线程中读写锁分离设计模式怎么用

发布时间:2021-10-28 13:36:02 来源:亿速云 阅读:132 作者:小新 栏目:开发技术

小编给大家分享一下Java多线程中读写锁分离设计模式怎么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

主要完成任务:

  • 1.read read 并行化

  • 2.read write 不允许

  • 3.write write 不允许

public class ReaderWorker extends Thread {

    private final SharedData data;

    public ReaderWorker(SharedData data) {
        this.data = data;
    }

    @Override
    public void run() {
        while (true) {
            try {
                char[] readBuf = data.read();
                System.out.println(Thread.currentThread().getName() + " reads " + String.valueOf(readBuf));

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
public class ReadWriteLock {

    /**
     * 当前有几个线程 在对它进行读操作
     */
    private int readingReaders = 0;
    /**
     * 当前有几个线程 等待读操作
     */
    private int waitingReaders = 0;

    /**
     * 当前有几个线程 正在写操作
     */
    private int writingWriters = 0;
    /**
     * 当前有几个线程 正在写操作
     */
    private int waitingWriters = 0;

    /**
     * 偏向于写
     */
    private boolean preferWriter = true;

    public ReadWriteLock() {
        this(true);
    }

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

    public synchronized void readLock() throws InterruptedException {
        this.waitingReaders++;
        try {
            /**
             * 让写的线程先运行
             */
            while (writingWriters > 0||(preferWriter&&waitingWriters>0)) {
                this.wait();
            }
            this.readingReaders++;
        } finally {
            this.waitingReaders--;
        }
    }

    public synchronized void readUnLock() {
        this.readingReaders--;
        this.notifyAll();
    }

    public synchronized void writeLock() throws InterruptedException {
        this.waitingWriters++;
        try {

            while (readingReaders > 0 || writingWriters > 0) {
                this.wait();
            }

            this.writingWriters++;
        } finally {
            this.waitingWriters--;
        }
    }

    public synchronized void writeUnlock() {
        this.writingWriters--;
        this.notifyAll();
    }
}



public class SharedData {

    private final char[] buffer;
    private final ReadWriteLock lock = new ReadWriteLock();

    public SharedData(int size) {
        this.buffer = new char[size];
        for (int i = 0; i < size; i++) {
            this.buffer[i] = '*';
        }
    }

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

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

    private void doWrite(char c) {
        for (int i = 0; i < buffer.length; i++) {
            buffer[i] = c;
            slowly(10);
        }
    }

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

    private void slowly(int millisecond) {
        try {
            Thread.sleep(millisecond);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class WriterWorker extends Thread {

    private static final Random random = new Random(System.currentTimeMillis());

    private final SharedData data;
    private final String filter;

    private int index = 0;

    public WriterWorker(SharedData data, String filter) {
        this.data = data;
        this.filter = filter;
    }

    @Override
    public void run() {

        try {

            while (true) {
                char c = nextChar();

                data.write(c);

                Thread.sleep(random.nextInt(1000));

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private char nextChar() {

        char c = filter.charAt(index);
        index++;
        if (index >= filter.length())
            index = 0;
        return c;
    }
}
/**
 *
 * ReadWriteLock
 */
public class ReadWriteLockClient {
    public static void main(String[] args) {
        final  SharedData sharedData = new SharedData(10);

        new ReaderWorker(sharedData).start();
        new ReaderWorker(sharedData).start();
        new ReaderWorker(sharedData).start();
        new ReaderWorker(sharedData).start();
        new ReaderWorker(sharedData).start();
        new WriterWorker(sharedData,"123456").start();
        new WriterWorker(sharedData,"abcdef").start();
    }
}

结果:

Thread-0 reads **********
Thread-1 reads **********
Thread-2 reads **********
Thread-3 reads **********
Thread-1 reads aaaaaaaaaa
Thread-3 reads aaaaaaaaaa
Thread-0 reads aaaaaaaaaa
Thread-2 reads aaaaaaaaaa
Thread-1 reads aaaaaaaaaa
Thread-2 reads aaaaaaaaaa
Thread-0 reads aaaaaaaaaa
Thread-3 reads aaaaaaaaaa
Thread-1 reads aaaaaaaaaa
Thread-3 reads aaaaaaaaaa
Thread-0 reads aaaaaaaaaa
Thread-2 reads aaaaaaaaaa
Thread-2 reads aaaaaaaaaa
Thread-0 reads aaaaaaaaaa
Thread-1 reads aaaaaaaaaa
Thread-3 reads aaaaaaaaaa
Thread-2 reads aaaaaaaaaa
Thread-0 reads aaaaaaaaaa
Thread-1 reads aaaaaaaaaa
Thread-3 reads aaaaaaaaaa
Thread-0 reads bbbbbbbbbb
Thread-1 reads bbbbbbbbbb
Thread-2 reads bbbbbbbbbb
Thread-3 reads bbbbbbbbbb
Thread-0 reads bbbbbbbbbb
Thread-1 reads bbbbbbbbbb
Thread-3 reads bbbbbbbbbb
Thread-2 reads bbbbbbbbbb
Thread-0 reads bbbbbbbbbb
Thread-1 reads bbbbbbbbbb
Thread-2 reads bbbbbbbbbb
Thread-3 reads bbbbbbbbbb
Thread-0 reads bbbbbbbbbb
Thread-1 reads bbbbbbbbbb
Thread-3 reads bbbbbbbbbb
Thread-2 reads bbbbbbbbbb
Thread-1 reads 3333333333
Thread-2 reads 3333333333
Thread-3 reads 3333333333
...... 省略

以上是“Java多线程中读写锁分离设计模式怎么用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI