Java基础-Queue队列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wanlong360599336/article/details/60757162

1.效果:

用cmd运行结果:

用Eclipse运行结果:

2.代码:

public class QueueStudy {

    public static void main(String[] args) {
        Queue q=new Queue();
        Producter p=new Producter(q);
        Customer c=new Customer(q);
        p.start();
        c.start();
    }
}

//生产者
class Producter extends Thread{
    Queue q;
    Producter(Queue q){
        this.q=q;
    }
    
    public void run(){
        for(int i=1;i<6;i++)
        {
            q.put(i);//推送数据
        }
    }
}

//消费者
class Customer extends Thread{
    Queue q;
    Customer(Queue q){
        this.q=q;
    }
    
    public void run(){
        while(true){//循环获取数据
            q.get();
        }
    }
}

//队列通知与接收数据
class Queue{
    int count=0;
    boolean isEmpty=true;
    //生产者生产数据
    public synchronized void put(int i){
        if(!isEmpty){//如果生产者生产的数据不为空,则一直等待,直到数据为空
            try{
                System.out.println("Product wait ...");
                wait();
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
        count+=i;
        isEmpty=false;
        System.out.println("producter totoal product:"+i);
        notify();//通知消费者数据已生产,请消费数据
    }
    //消费者消费数据
    public synchronized void get(){
        if(isEmpty){//如果数据为空,消费者等待生产者生产数据,直到有数据为止
            try{
                System.out.println("Customer wait ...");
                System.out.println("");
                wait();
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
        count--;
        if(count==0){
            isEmpty=true;
            notify();//通知生产者数据已空,请生产者生产数据
        }
        System.out.println("Customer spend :"+count);
    }
}



猜你喜欢

转载自blog.csdn.net/wanlong360599336/article/details/60757162
今日推荐