欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

生产者和消费者

程序员文章站 2022-07-12 17:37:44
...

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


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();
            }
        }

    }

}