一个线程作为生产者,一个线程作为消费者。生产者每生产一次,消费者就消费一次。生产者每次生产一定数量的商品,加上上次消费剩余的数量,而总数量不超过1000;总感觉代码不是很完善,求指教??

/**
 * 一个线程作为生产者,一个线程作为消费者。生产者每生产一次,消费者就消费一次。
 * 生产者每次生产一定数量的商品,加上上次消费剩余的数量作为本次所提供的总数量,
 * 而总数量不超过1000;消费者则在生产者本次提供的总数量的前提下进行消费。
 * 每次生产和消费的数量可以利用随机数计算,但是每次生产的总数量加上上次剩余的数量不能超过1000;
 * 每次消费的数量不能超过本次生产的数量。
 * @author Gavin_W_
 *
 */
//商品类
class Store{
    static int value=0;
    static boolean flag;
    public Store(int value) {
        Store.value = value;
    }
}
//生产者
class Producer implements Runnable{
    @Override
    public void run() {
        
            while(true){
            synchronized (ThreadDemo.class) {
                try {
                    if(Store.flag==true){
                        ThreadDemo.class.wait();
                    }
                    System.out.println("仓库剩余商品数"+Store.value);
                    int proNum=(int) (Math.random()*1000);
                    Thread.sleep(1000);
                    
                    while(proNum>=(1000-Store.value)){
                        proNum=(int) (Math.random()*1000);
                    }
                    System.out.println("生产了"+proNum);
                    Store.value += proNum;
                    
                    Store.flag=true;
                    ThreadDemo.class.notify();                                
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
            }
        }
        
    }
    
}
//消费者
class Spend implements Runnable{
    @Override
    public void run() {
        
            while(true){
                synchronized (ThreadDemo.class) {
                try {
                
                    if(Store.flag==false){            
                        ThreadDemo.class.wait();
                    }
                    System.out.println("仓库剩余商品数量"+Store.value);
                    int speNum = (int) (Math.random()*1000);
                    Thread.sleep(1000);
                    while(speNum>Store.value||speNum==0){
                        speNum = (int) (Math.random()*1000);
                    }
                    System.out.println("消费了"+speNum);
                    Store.value -= speNum;
                    Store.flag=false;
                    ThreadDemo.class.notify();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            
                
            }
            }
        }
        
    }
//测试线程
public class ThreadDemo {    
    public static void main(String[] args) {
        new Thread(new Producer()).start();
        new Thread(new Spend()).start();
    }
}

 

posted @ 2018-09-09 14:26  南岭寒  Views(186)  Comments(0Edit  收藏  举报