|
| 1 | +/** |
| 2 | + * @Description: 改变拿筷子的顺序解决问题 |
| 3 | + * @Author: zzStar |
| 4 | + * @Date: 2020/10/21 09:13 |
| 5 | + */ |
| 6 | +public class SolveDinningPhilosophersProblem { |
| 7 | + |
| 8 | + public static void main(String[] args) { |
| 9 | + Philosopher[] philosophers = new Philosopher[5]; |
| 10 | + Object[] chopsticks = new Object[philosophers.length]; |
| 11 | + // 初始化筷子 |
| 12 | + for (int i = 0; i < chopsticks.length; i++) { |
| 13 | + chopsticks[i] = new Object(); |
| 14 | + } |
| 15 | + for (int i = 0; i < philosophers.length; i++) { |
| 16 | + Object leftChopstick = chopsticks[i]; |
| 17 | + Object rightChopstick = chopsticks[(i + 1) % chopsticks.length]; |
| 18 | + |
| 19 | + // 到了最后一位哲学家 |
| 20 | + if (i == philosophers.length - 1) { |
| 21 | + philosophers[i] = new Philosopher(rightChopstick, leftChopstick); |
| 22 | + } else { |
| 23 | + philosophers[i] = new Philosopher(leftChopstick, rightChopstick); |
| 24 | + } |
| 25 | + |
| 26 | + new Thread(philosophers[i], "哲学家" + (i + 1) + "号").start(); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + public static class Philosopher implements Runnable { |
| 31 | + private Object leftChopstick; |
| 32 | + private Object rightChopstick; |
| 33 | + |
| 34 | + public Philosopher(Object leftChopstick, Object rightChopstick) { |
| 35 | + this.leftChopstick = leftChopstick; |
| 36 | + this.rightChopstick = rightChopstick; |
| 37 | + } |
| 38 | + |
| 39 | + @Override |
| 40 | + public void run() { |
| 41 | + try { |
| 42 | + while (true) { |
| 43 | + doAction("Thinking"); |
| 44 | + synchronized (leftChopstick) { |
| 45 | + doAction("First I pick up left chopstick"); |
| 46 | + synchronized (rightChopstick) { |
| 47 | + doAction("Then I get the right chopstick,so I start eating"); |
| 48 | + doAction("Put down right chopstick"); |
| 49 | + } |
| 50 | + doAction("Put down left chopstick"); |
| 51 | + } |
| 52 | + } |
| 53 | + } catch (InterruptedException e) { |
| 54 | + e.printStackTrace(); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + private void doAction(String action) throws InterruptedException { |
| 59 | + System.out.println(Thread.currentThread().getName() + "" + action); |
| 60 | + Thread.sleep((long) (Math.random() * 10)); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + |
| 65 | +} |
0 commit comments