Java:多线程生产者消费者

public class ProducerConsumer{
    public static void main(String[] args) {
        StackContent sc = new StackContent();
        Producer p = new Producer(sc);
        Consumer c  = new Consumer(sc);
        new Thread(p).start();
        new Thread(c).start();
    }
}



class ManTou{
    private int num;
    public ManTou(int num){
        this.num = num;
    }

    public String toString(){
        return "馒头" + this.num;
    }
}


class StackContent{
    private ManTou[] sc = new ManTou[6];
    int index = 0;
    public synchronized void push(ManTou m){
        while(index == sc.length){
            try{
                this.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        this.notifyAll();
        sc[index] = m;
        System.out.println("push 位置:"+index + "    生产了馒头:"+m);
        index ++;
    }

    public synchronized ManTou pop(){
        while(index == 0){
            try{
                this.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        this.notifyAll();
        index --;
        System.out.println("pop  位置:"+index+"    消费了馒头:"+sc[index]);
        return sc[index];
    }
}

class Producer implements Runnable{
    private StackContent sc = null;
    public Producer(StackContent sc){
        this.sc = sc;
    }
    public void run(){
        for(int i = 0; i < 10; i++){
            ManTou m = new ManTou(i);
            sc.push(m);
            // System.out.println("生产了:"+m); 
            try{
                Thread.sleep(10);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        
    }
}

class Consumer implements Runnable{
    private StackContent sc = null;
    public Consumer(StackContent sc){
        this.sc = sc;
    }
    public void run(){
        for(int i = 0; i < 10; i++){
            ManTou m  = sc.pop();
            // System.out.println("消费了:"+m);
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        
    }
    
}

posted @ 2016-07-05 22:49  桃源仙居  阅读(99)  评论(0)    收藏  举报