生产者消费者模式 多线程

来源:互联网 发布:淘宝弹弓狙击鹰七 编辑:程序博客网 时间:2024/06/06 01:08

生产者消费者模式 多线程

1.使用synchronized,wait(),notifyAll();

public class Product {    private String name;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Product(String name) {        super();        this.name = name;    }}
import java.util.ArrayList;import java.util.List;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;import java.util.concurrent.locks.Condition;public class Container<T> {    private int maxSize;    private List<T> list;    public Container(int maxSize) {        this.maxSize = maxSize;        list = new ArrayList<T>(maxSize);    }    /**     * 生产产品放入容器     *      * @param product     */    public synchronized void add(T product) {        try {            while (list.size() >= maxSize) {                wait();            }            notifyAll();            System.out.println(Thread.currentThread().getName() + ":add:"                    + list.size());            list.add(product);        } catch (InterruptedException e) {            e.printStackTrace();        }    }    /**     * 从容器取出产品     *      * @return     */    public synchronized T take() {        try {            while (list.size() <= 0) {                wait();            }            notifyAll();            System.out.println(Thread.currentThread().getName() + ":take:"                    + list.size());            return list.remove(0);        } catch (InterruptedException e) {            e.printStackTrace();        }        return null;    }    /**     * 容器是否满     *      * @return     */    public boolean isFull() {        synchronized (list) {            if (list.size() >= maxSize) {                return true;            }            return false;        }    }    /**     * 容器是否为空     *      * @return     */    public boolean isEmpty() {        synchronized (list) {            return list.isEmpty();        }    }    public int getSize() {        synchronized (list) {            return list.size();        }    }    public int getMaxSize() {        return maxSize;    }}
public class Producer implements Runnable {    private Integer name;    private Container<Product> container;    public Producer(Container<Product> container) {        super();        this.container = container;    }    @Override    public void run() {        while (true) {            produce();        }    }    public void produce() {        try {            Thread.sleep(250);        } catch (InterruptedException e) {            e.printStackTrace();        }        name = container.getSize();        Product product = new Product(name.toString());        container.add(product);    }}
public class Consumer implements Runnable {    private Container<Product> container;    public Consumer(Container<Product> container) {        super();        this.container = container;    }    @Override    public void run() {        while (true) {            consume();        }    }    public void consume() {        try {            Thread.sleep(500);        } catch (InterruptedException e) {            e.printStackTrace();        }        container.take();    }}
public class Client {    public static void main(String[] args) {        Container container = new Container<Product>(10);        Producer producer = new Producer(container);        Consumer consumer = new Consumer(container);        Thread threadProducer = new Thread(producer);        Thread threadConsumer = new Thread(consumer);        threadProducer.start();        threadConsumer.start();    }}

2.使用lock,Condition,await(),signalAll();

修改Container.java

    private final Lock lock;    private final Condition notFull;    private final Condition notEmpty;    public Container(int maxSize) {        this.maxSize = maxSize;        list = new ArrayList<T>(maxSize);        lock = new ReentrantLock();        notFull = lock.newCondition();        notEmpty = lock.newCondition();    }    /**     * 生产产品放入容器     *      * @param product     */    public void add(T product) {        lock.lock();        try {            while (list.size() >= maxSize) {                System.out.println(Thread.currentThread().getName() + " wait");                notFull.await();            }            list.add(product);            System.out.println(Thread.currentThread().getName() + ":add:"                    + list.size());            notEmpty.signalAll();        } catch (InterruptedException e) {            e.printStackTrace();        } finally {            lock.unlock();        }    }    /**     * 从容器取出产品     *      * @return     */    public T take() {        lock.lock();        try {            while (list.size() <= 0) {                System.out.println(Thread.currentThread().getName() + " wait");                notEmpty.await();            }            T temp = list.remove(0);            System.out.println(Thread.currentThread().getName() + ":take:"                    + list.size());            notFull.signalAll();            return temp;        } catch (InterruptedException e) {            e.printStackTrace();        } finally {            lock.unlock();        }        return null;    }
原创粉丝点击