thread25

来源:互联网 发布:微信抓取朋友圈数据库 编辑:程序博客网 时间:2024/05/01 12:37
package com.neutron.t18;import java.util.LinkedList;import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/** * 写一个固定容量的同步容器,拥有put和get方法,以及getCount方法。 * 能够支撑2个生产者线程,以及10个消费者线程的阻塞调用 * * 所谓同步容器,即如果容量满了,那么put阻塞;如果容量空了,那么get阻塞等待。 * 使用wait和notify/notifyAll来实现 * * 除了使用wait和notify/notifyAll * 还可以使用Lock和Condition来实现 * 对比两种方式,Condition的方式可以更加精确第指定哪些线程被唤醒 */public class T182<T> {    // 同步容器    private final LinkedList<T> lists = new LinkedList<>();    // 容器最大容量    private final int MAX = 10;    // 容器数据个数计数器,个人认为加上volatile效果更好    private /*volatile*/ int count = 0;    private Lock lock = new ReentrantLock();            // 锁    private Condition producer = lock.newCondition();   // 生产者条件    private Condition consumer = lock.newCondition();   // 消费者条件    public void put(T t) {        lock.lock();        try {            while (lists.size() == MAX) {                producer.await();                       // 生产者线程等待            }            lists.add(t);            System.out.println("put : " + t);            count++;            consumer.signalAll();                       // 通知消费者线程进行消费,这个不必担心唤醒生产者线程        } catch (InterruptedException e) {            e.printStackTrace();        } finally {            lock.unlock();        }    }    public T get() {        T t = null;        lock.lock();        try {            while (lists.size() == 0) {                consumer.await();            }            t = lists.removeFirst();            System.out.println("get : " + t);            count--;            producer.signalAll();                       // 唤醒生产者线程        } catch (InterruptedException e) {            e.printStackTrace();        }        return t;    }    public static void main(String[] args) {        T182<String> r1 = new T182();        // 创建10个消费者线程        for (int i = 0; i < 10; i++) {            new Thread(() -> {                for (int j = 0; j < 5; j++) {                    r1.get();                }            }).start();        }        try {            TimeUnit.SECONDS.sleep(2);        } catch (InterruptedException e) {            e.printStackTrace();        }        // 创建2个生产者线程        for (int i = 0; i < 2; i++) {            new Thread(() -> {                for (int j = 0; j < 5; j++) {                    r1.put(Thread.currentThread().getName() + " "+ j);                }            }, "p" + i).start();        }    }}

原创粉丝点击