Java實現PV操作 | 哲學家進餐問題

來源:互聯網
上載者:User

標籤:ace   syn   img   color   等於   .com   技術分享   ilo   zed   

運行結果:

 

Java代碼:

 1 public class Main { 2  3     public static void main(String[] args) { 4         Global global=new Global(); 5          6         philosopher ph[]=new philosopher[5]; 7         int i; 8         for(i=0;i<5;i++){ 9             ph[i]=new philosopher(i);10         }11         Thread[] ph_t=new Thread[5];12         for(i=0;i<5;i++){13             ph_t[i]=new Thread(ph[i]);14         }15         for(i=0;i<5;i++){16             ph_t[i].start();17         }18     }19 }20 21 22 class syn{//PV操作類23     int count=0;//訊號量24     syn(){}25     syn(int a){count=a;}26     public synchronized void Wait(){ //關鍵字 synchronized 保證了此操作是一條【原語】27         count--;28         if(count<0){//等於0 :有一個進程進入了臨界區29             try {         //小於0:abs(count)=阻塞的進程數目30                 this.wait();31             } catch (InterruptedException e) {32                 e.printStackTrace();  33             }  34         }  35     }  36     public synchronized void Signal(){   //關鍵字 synchronized 保證了此操作是一條【原語】37         count++;38         if(count<=0){//如果有進程阻塞39             this.notify();//All40         }41     }  42 }43 44 class Global{45     static syn chopsticks[]=new syn[5];46     static int count=0;47     Global(){48         int i;49         for(i=0;i<5;i++){50             chopsticks[i]=new syn(1);//初始化訊號量51         }52     }53 }54 55 class philosopher implements Runnable{//哲學家類56     int ID=0;57     philosopher(){}58     philosopher(int id){59         ID=id;60     }61     public void run(){62         while(true){//Global.count<2063             //拿起左筷子64             Global.chopsticks[ID].Wait();65             Global.chopsticks[(ID+1)%5].Wait();66             67             Global.count++;68             System.out.println("哲學家"+ID+"拿起了筷子"+ID+"和筷子"+((ID+1)%5)+"美餐了一頓");69             try {70                 Thread.sleep(10);71             } catch (InterruptedException e) {72                 // TODO Auto-generated catch block73                 e.printStackTrace();74             }75             76             Global.chopsticks[ID].Signal();77             Global.chopsticks[(ID+1)%5].Signal();78         }79     }80 }

 

Java實現PV操作 | 哲學家進餐問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.