首页 > 代码库 > 线程学习五:哲学家就餐问题

线程学习五:哲学家就餐问题

问题描述:

设有5个哲学家,共享一张放有5把椅子的桌子,每人分得一把椅子,但是,桌子上共有5只筷子,在每人两边各放一只,哲学家们在肚子饥饿时才试图分两次从两边拿起筷子就餐。条件:1)拿到两只筷子时哲学家才开始吃饭。2)如果筷子已在他人手上,则该哲学家必须等他人吃完之后才能拿到筷子。3)任一哲学家在自己未拿到两只筷子前却不放下自己手中的筷子。

解题思路:

如果哲学家身边的2把筷子都没人使用,哲学家便可以就餐,否者哲学家只能等待别人就餐完毕。那么就根据哲学家身边的筷子状态做判断,满足条件便就餐,不满足则等待

代码:

 1 public class PhilosopherTest { 2     public static void main(String args[]) { 3         Philosopher pl = new philosopher1(); 4         Thread thread1 = new Thread(pl, "1"); 5         Thread thread2 = new Thread(pl, "2"); 6         Thread thread3 = new Thread(pl, "3"); 7         Thread thread4 = new Thread(pl, "4"); 8         Thread thread5 = new Thread(pl, "5"); 9         thread1.start();10         thread2.start();11         thread3.start();12         thread4.start();13         thread5.start();14     }15 16 }17 18 class Philosopher implements Runnable{19     private static boolean[] fork = { false, false, false, false, false};20 21     @Override22     public void run() {23         while (true) {24                 eating();25                 thinking();26         }27     }28 29     public synchronized void eating() {30         try{31             int i = Integer.parseInt(Thread.currentThread().getName());32             if (fork[i % 5] == false && fork[i - 1] == false){ 33             Thread.sleep(500);//模拟吃饭过程34             System.out.println("当前在吃饭的是" + Thread.currentThread().getName());35             fork[i % 5] = true;36             fork[i - 1] = true;37             }else{38                 wait();39             }40         }catch(Exception e){41             e.printStackTrace();42         }43     }44 45     public synchronized void thinking() {46         try{47             int i = Integer.parseInt(Thread.currentThread().getName());48             if (fork[i % 5] == true && fork[i - 1] == true) {49             Thread.sleep(500);//模拟思考过程50             System.out.println(Thread.currentThread().getName() + "已经吃完饭了");51             fork[i % 5] = false;52             fork[i - 1] = false;53             notifyAll();54             }55         }catch(Exception e){56             e.printStackTrace();57         }58 59     }60 }

 

线程学习五:哲学家就餐问题