码迷,mamicode.com
首页 > 编程语言 > 详细

多线程设计模式:第三篇 - 生产者-消费者模式和读写锁模式

时间:2018-10-18 18:10:39      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:end   链表实现   int   false   vat   优先   class   adl   OLE   

一,生产者-消费者模式

        生产者-消费者模式是比较常见的一种模式,当生产者和消费者都只有一个的时候,这种模式也被称为 Pipe模式,即管道模式。

        生产者-消费者模式中通过 Channel 即通道来互相传递数据,那么数据在通道中以什么样的顺序传递,这里在设计时需要考虑,一般的实现包括如下三种方式:

  • 队列——顺序传递
  • 栈——倒序传递
  • 优先队列——根据权重/优先权来传递

        Channel 通道可以通过 juc 包中的 BlockingQueue 来实现,这样省去了自己实现 Queue 时的 wait/notify 操作。一个简单的生产者-消费者模型举例:在该例子中,生产者是负责生成蛋糕并放到桌子上,消费者就负责从桌子上拿蛋糕吃,这里桌子作为数据传输的通道,其代码实现如下:

/**
 * @author koma <komazhang@foxmail.com>
 * @date 2018-10-18
 */
public class Table {
    private final Queue<String> queue;
    private final int count;

    public Table(int count) {
        this.count = count;
        queue = new LinkedList<>();
    }

    public synchronized void put(String cake) throws InterruptedException {
        System.out.println(Thread.currentThread().getName()+" puts "+cake);
        while (queue.size() >= count) {
            wait();
        }
        queue.offer(cake);
        notifyAll();
    }

    public synchronized String take() throws InterruptedException {
        while (queue.size() <= 0) {
            wait();
        }
        String cake = queue.poll();
        notifyAll();
        System.out.println(Thread.currentThread().getName()+" takes "+cake);
        return cake;
    }
}

        生产者,消费者以及启动类代码如下:

/**
 * @author koma <komazhang@foxmail.com>
 * @date 2018-10-18
 */
public class Main {
    public static void main(String[] args) {
        Table table = new Table(3);
        new MakerThread("MakerThread-1", table, 314151).start();
        new MakerThread("MakerThread-2", table, 523242).start();
        new MakerThread("MakerThread-3", table, 716151).start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new EaterThread("EaterThread-1", table, 625341).start();
        new EaterThread("EaterThread-2", table, 525349).start();
        new EaterThread("EaterThread-3", table, 225841).start();
    }
}

public class EaterThread extends Thread {
    private final Random random;
    private final Table table;

    public EaterThread(String name, Table table, long seed) {
        super(name);
        this.table = table;
        this.random = new Random(seed);
    }

    @Override
    public void run() {
        try {
            while (true) {
                String cake = table.take();
                Thread.sleep(random.nextInt(1000));
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class MakerThread extends Thread {
    private final Random random;
    private final Table table;
    private static int id = 0;

    public MakerThread(String name, Table table, long seed) {
        super(name);
        this.table = table;
        this.random = new Random(seed);
    }

    @Override
    public void run() {
        try {
            while (true) {
                Thread.sleep(random.nextInt(1000));
                String cake = "[ Cake No."+nextId()+" by "+getName()+" ]";
                table.put(cake);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static synchronized int nextId() {
        return id++;
    }
}

        如果 Table 类选择使用 juc 包中的 BlockingQueue 来实现,则非常简单。常见的 BlockingQueue 包括基于链表实现的 LinkedBlockingQueue,基于数组实现的 ArrayBlockingQueue,以及带有优先级的 PriorityBlockingQueue。这里我们使用基于链表的 BlockingQueue,改写之后代码如下:

/**
 * @author koma <komazhang@foxmail.com>
 * @date 2018-10-18
 */
public class Table {
    private final LinkedBlockingQueue<String> queue;
    private final int count;

    public Table(int count) {
        this.count = count;
        queue = new LinkedBlockingQueue<>();
    }

    public synchronized void put(String cake) throws InterruptedException {
        System.out.println(Thread.currentThread().getName()+" puts "+cake);
        queue.put(cake);
    }

    public synchronized String take() throws InterruptedException {
        System.out.println(Thread.currentThread().getName()+" takes "+cake);
        return queue.take();
    }
}

二,读写锁模式

        读写锁模式是一种把读操作和写操作分开来考虑的模式,在这种模式下一个实例包括两类锁:读锁和写锁。写锁可由多个线程同时获取,而读锁只能由一个线程同时获取。而且规定在执行写操作时不能进行读写,在执行读操作时不能进行写。

        一般来说,执行互斥处理会降低程序性能,但是如果把读写操作分开来考虑则可以提高程序性能。

        下面的示例代码,使用读写锁模式来实现对 Data 类的读写操作,其中最关键的是 ReadWriteLock 类,该类使用到了不可变模式。

/**
 * @author koma <komazhang@foxmail.com>
 * @date 2018-10-18
 */
public class Main {
    public static void main(String[] args) {
        Data data = new Data(10);
        new ReaderThread(data).start();
        new ReaderThread(data).start();
        new ReaderThread(data).start();
        new ReaderThread(data).start();
        new ReaderThread(data).start();
        new ReaderThread(data).start();
        new WriterThread(data, "ABCDEFGHIJKLMNOPQRSTUVWXYZ").start();
        new WriterThread(data, "abcdefghijklmnopqrstuvwxyz").start();
    }
}

public class Data {
    private final char[] buffer;
    private final ReadWriteLock lock = new ReadWriteLock();

    public Data(int size) {
        this.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();
        }
    }

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

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

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

    private void slowly() {
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class ReaderThread extends Thread {
    private final Data data;

    public ReaderThread(Data data) {
        this.data = data;
    }

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

public class WriterThread extends Thread {
    private final static Random random = new Random();
    private final Data data;
    private final String filler;
    private int index = 0;

    public WriterThread(Data data, String filler) {
        this.data = data;
        this.filler = filler;
    }

    @Override
    public void run() {
        try {
            while (true) {
                char c = nextChar();
                data.write(c);
                Thread.sleep(random.nextInt(3000));
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private char nextChar() {
        char c = filler.charAt(index);
        index++;
        if (index >= filler.length()) {
            index = 0;
        }
        return c;
    }
}

public final class ReadWriteLock {
    private int readingReaders = 0; //正在执行读操作的线程数
    private int waitingWriters = 0; //等待写锁的线程数
    private int writingWriters = 0; //正在执行写操作的线程数
    private boolean preferWriter = true; //是否写入优先

    public synchronized void readLock() throws InterruptedException {
        while (writingWriters > 0 || (preferWriter && waitingWriters > 0)) {
            wait();
        }

        readingReaders++;
    }

    public synchronized void readUnlock() {
        readingReaders--;
        preferWriter = true;
        notifyAll();
    }

    public synchronized void writeLock() throws InterruptedException {
        waitingWriters++;
        try {
            while (readingReaders > 0 || writingWriters > 0) {
                wait();
            }
        } finally {
            waitingWriters--;
        }
        writingWriters++;
    }

    public synchronized void writeUnlock() {
        writingWriters--;
        preferWriter = false;
        notifyAll();
    }
}

        读写锁模式利用了读操作不修改实例状态的特性,这样多个读操作线程之间就不存在冲突,因此不用做同步处理,从而提供程序性能。但是性能的提升不是绝对的,需要实际测量,同时也需要考虑以下两个场景要求:

  • 读取操作耗时的操作,当读取操作很简单时,单线程模式相比而言更加简单高效
  • 读取频率比写入频率高的操作,当写入频率较高时,写入操作频繁的打断读取操作,读写锁模式的优越性降低

1,锁的含义

        synchronized 是用于获取实例的锁。Java 中每个对象的实例都持有一个锁,但同一个锁同时只能由一个线程持有。这种结构是 Java 规范规定的,JVM 也是这么实现的。这种锁称为物理锁

        在读写锁模式中,这里的锁与 synchronized 获取的锁是不一样的,这并不是 Java 规范规定的锁,而是由开发人员自己实现的,这种锁称为逻辑锁

        ReadWriteLock 类中有读锁和写锁,但这是逻辑锁,这两个逻辑锁共用同一个由 synchronized 获取的 ReadWriteLock 类实例的物理锁。这就是为什么我们在 ReadWriteLock 类中的加锁、解锁方法上都声明了 synchronized 关键字的缘故,因为它们最终要共用同一把物理锁,而同一把物理锁同一时间只能由一个线程持有,这种规定保证了逻辑锁的实现。

2,Java 中的读写锁

        在 juc 包中提供了实现了读写锁模式的 ReadWriteLock 接口和 ReentrantReadWriteLock 实现类。通过 ReentrantReadWriteLock 改写之后的 Data 类代码如下:

/**
 * @author koma <komazhang@foxmail.com>
 * @date 2018-10-18
 */
public class Data {
    private final char[] buffer;
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private final Lock readLock = lock.readLock();
    private final Lock writeLock = lock.writeLock();

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

    public char[] read() throws InterruptedException {
        readLock.lock();
        try {
            Thread.sleep(10000);
            return doRead();
        } finally {
            readLock.unlock();
        }
    }

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

    //其它方法不变

多线程设计模式:第三篇 - 生产者-消费者模式和读写锁模式

标签:end   链表实现   int   false   vat   优先   class   adl   OLE   

原文地址:http://blog.51cto.com/13975879/2304357

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!