国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

Java基礎-Queue隊列

2019-11-06 06:13:56
字體:
來源:轉載
供稿:網友

1.效果:

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


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 阜阳市| 惠东县| 同心县| 六安市| 商城县| 宽城| 莎车县| 唐河县| 三河市| 静海县| 汉阴县| 九台市| 张家界市| 肥城市| 莎车县| 民丰县| 大荔县| 保山市| 峨山| 盐山县| 屏东县| 务川| 大理市| 儋州市| 郑州市| 宜兴市| 阿瓦提县| 崇义县| 曲阳县| 合山市| 阿勒泰市| 宜州市| 砚山县| 茶陵县| 江津市| 滨海县| 游戏| 青阳县| 桃园县| 江都市| 杭州市|