中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

java多線程示例 模擬生產(chǎn)者消費者

2018-07-20    來源:open-open

容器云強勢上線!快速搭建集群,上萬Linux鏡像隨意使用
public class ProducerConsumer {

    public static void main(String[] args) {
        SyncStack ss=new SyncStack();
        Producer pro=new Producer(ss);
        Consumer con=new Consumer(ss);
        new Thread(pro).start();
        new Thread(pro).start();
        new Thread(con).start();

    }

}
class Product{
    int id;
    public Product(int id){
        this.id=id;
    }
    public String toString(){//重寫toString 方法,給pro加上編號,以便調(diào)試
        return "product   "+id;
    }
}
class SyncStack{//棧,先進后出
    Product[] proArr=new Product[6];//定義容器只能裝6件產(chǎn)品
    int index=0;
    public synchronized void push(Product pro){
        while(index==proArr.length){//當容器裝滿了產(chǎn)品,暫停生產(chǎn)
            try{
                this.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        this.notifyAll();//喚醒消費者消費
        proArr[index]=pro;
        index++;

    }
    public synchronized Product pop(){//同步,確保不被打斷
        while(index==0){//當容器里沒有產(chǎn)品可消費,暫停消費
            try{
                this.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        this.notifyAll();//喚醒生產(chǎn)者生產(chǎn)
        index--;
        return proArr[index];
    }
}
class Producer implements Runnable{
    SyncStack ss=null;
    public Producer(SyncStack ss){
        this.ss=ss;
    }
    public void run() {
        for(int i=0;i<20;i++){
            Product pro=new Product(i);
            ss.push(pro);
            System.out.println("生產(chǎn)了:"+pro);
            try{//方便觀察結果,沒有實際意義
                Thread.sleep((int)(Math.random()*200));
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
class Consumer implements Runnable{
    SyncStack ss=null;
    public Consumer(SyncStack ss){
        this.ss=ss;
    }
    public void run(){
        for(int i=0;i<20;i++){
            Product pro=ss.pop();
            System.out.println("消費了:"+pro);
            try{//方便觀察結果,沒有實際意義
                Thread.sleep((int)(Math.random()*1000));
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

標簽:

版權申明:本站文章部分自網(wǎng)絡,如有侵權,請聯(lián)系:west999com@outlook.com
特別注意:本站所有轉載文章言論不代表本站觀點!
本站所提供的圖片等素材,版權歸原作者所有,如需使用,請與原作者聯(lián)系。

上一篇:類似log4cplus的一個C++日志類

下一篇:一個根據(jù)URI定位到spring mvc映射代碼工具類