生产者和消费者

2018-01-11 17:23:53 浏览数 (1)

用到 wait()、notify()/notifyAll()方法

代码语言:javascript复制
public class Test15 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        AppleBox ab=new AppleBox();
        Producer p=new Producer(ab);

        Consumer c=new Consumer(ab);
        Consumer cd=new Consumer(ab);

        new Thread(p).start();
        new Thread(c).start();
        new Thread(cd).start();


    }



}
//消息的对象=>消息
class Apple{
    int id;
    Apple(int id){
        this.id=id;
    }

    public String toString(){
        return "apple"  id;
    }

}
//容器
class AppleBox{
    int index=0;
    Apple[] apples=new Apple[5];

    public synchronized void deposite(Apple apple){
        while(index==apples.length){
            try {
                this.wait();    //wait是Object 对象的方法  =>将这个对象所在的线程阻塞住  释放对象锁
            } catch (InterruptedException e) {

                e.printStackTrace();
            }
        }

        this.notifyAll();//notifyAll也是Object对象的方法  =>通知其他线程启动

        apples[index]=apple;
        index  ;
    }

    public synchronized Apple withdraw(){
        while(index==0){
            try {
                this.wait();
            } catch (InterruptedException e) {

                e.printStackTrace();
            }
        }

        this.notifyAll();


        index--;
        return apples[index];

    }


}

class Producer implements Runnable{
    AppleBox ab=null;

    Producer(AppleBox ab) {
        this.ab=ab;
    }

    @Override
    public void run() {
        for(int i=0;i<20;i  ){
            Apple a=new Apple(i);
            ab.deposite(new Apple(i));
            System.out.println(Thread.currentThread().getName() "生产了" a);

            try {
                Thread.sleep((int)(Math.random()*1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}

class Consumer implements Runnable{

    AppleBox ab=null;
    public Consumer(AppleBox ab) {
        this.ab=ab;
    }

    @Override
    public void run() {
        for(int i=0;i<20;i  ){
            Apple a=ab.withdraw();

            System.out.println(Thread.currentThread().getName() "消费了" a);

            try {
                Thread.sleep((int)(Math.random()*1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}

0 人点赞