国产探花免费观看_亚洲丰满少妇自慰呻吟_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);    }}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 湘潭县| 民勤县| 张家港市| 巴里| 湟中县| 临桂县| 康平县| 屏南县| 广西| 南宫市| 南宁市| 广汉市| 新郑市| 本溪市| 阜宁县| 扎兰屯市| 武陟县| 资中县| 阿图什市| 宁乡县| 兴海县| 同德县| 咸宁市| 新化县| 丰县| 且末县| 团风县| 平武县| 武威市| 黄平县| 武定县| 壶关县| 辽宁省| 石屏县| 南江县| 墨竹工卡县| 田林县| 古浪县| 安龙县| 石河子市| 五莲县|