zoukankan      html  css  js  c++  java
  • Java实现PV操作 | 哲学家进餐问题

    运行结果:

    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();//All
    40         }
    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<20
    63             //拿起左筷子
    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 block
    73                 e.printStackTrace();
    74             }
    75             
    76             Global.chopsticks[ID].Signal();
    77             Global.chopsticks[(ID+1)%5].Signal();
    78         }
    79     }
    80 }
  • 相关阅读:
    IDEA 中 右键新建时,没有新建class的解决方案
    Git--删除远程仓库文件但不删除本地仓库资源
    Git——跟踪或取消跟踪文件
    git命令大杂烩
    判断项目中是否有slf4j的实现类
    完美解决在Servlet中出现一个输出中文乱码的问题
    mysql常用命令和语句
    设置idea快速生成doc comment
    关于pom.xml中的dependency中的顺序
    Pyqt5_QMessageBox
  • 原文地址:https://www.cnblogs.com/TQCAI/p/7709805.html
Copyright © 2011-2022 走看看