多线程简单实例(2)生产者和消费者

这是一个生产者和消费者的例子。消费者从仓库取物品,生产者向仓库增加商品。

当商品说达到最大时,不能继续增加商品,应该通知其他线程去取商品。

同样,当仓库商品为空时,无法取商品,而是通知其他线程增加商品。

这里用到线程的两个常用的方法:notifyAll和wait方法。

package code.thread;
//Product and Custom
public class ProAndCus {
    public static void main(String[] args) {
        Store store = new Store(10);
        Custom custom = new Custom(store);
        Product product = new Product(store);
        Custom custom2 = new Custom(store);
        Product product2 = new Product(store);
        
        custom.start();
        product.start();
        custom2.start();
        product2.start();
    }
}
//商品仓库
class Store {
    //最大储存商品数
    private final int MAX_SIZE;
    //当前商品数
    private int count;
    
    public Store(int size) {
        MAX_SIZE = size;
        count = 0;
    }
    
    //增加商品
    public synchronized void add() {
        if(count>=MAX_SIZE) {
            System.out.println(Thread.currentThread().getName()+"  Store is full, please to get. count:"+count);
            try{
                this.wait();
            }catch(InterruptedException e) {
                e.printStackTrace();
            }
        }else{
            System.out.println(Thread.currentThread().getName()+" custom :current count: "+count);
            count++;
            this.notifyAll();
        }
    }
    
    //移除商品
    public synchronized void remove() {
        if(count<=0) {
            System.out.println(Thread.currentThread().getName()+"  Store is empty,please input.  count:"+count);
            try{
                this.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }else{
            count--;
            System.out.println(Thread.currentThread().getName()+"  product: current count: "+count);
            this.notifyAll();
        }
    }
}
//消费者
class Custom extends Thread {
    Store store;
    public Custom(Store store) {
        this.store = store;
    }
    @Override
    public void run() {
        while(true){
            store.remove();
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
//生产者
class Product extends Thread {
    Store store;
    public Product(Store store) {
        this.store = store;
    }
    
    @Override
    public void run() {
        while(true){
            store.add();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

 

posted @ 2017-06-18 17:49  torjan  阅读(252)  评论(0编辑  收藏  举报