哲学家吃饭问题模拟(java写的)
这里是两种算法,公用一个chopstick类:
Chopstick类:
dining类public class Dining2 {/** * @param args */public static void main(String[] args) {Chopstick chopstick1 = new Chopstick("筷子 1 ");Chopstick chopstick2 = new Chopstick("筷子 2 ");Chopstick chopstick3 = new Chopstick("筷子 3 ");Chopstick chopstick4 = new Chopstick("筷子 4 ");Chopstick chopstick5 = new Chopstick("筷子 5 ");Philosopher2 philosopher1 = new Philosopher2("哲学家 1 ", chopstick5,chopstick1);Philosopher2 philosopher2 = new Philosopher2("哲学家 2 ", chopstick1,chopstick2);Philosopher2 philosopher3 = new Philosopher2("哲学家 3 ", chopstick2,chopstick3);Philosopher2 philosopher4 = new Philosopher2("哲学家 4 ", chopstick3,chopstick4);Philosopher2 philosopher5 = new Philosopher2("哲学家 5 ", chopstick4,chopstick5);long startTime = System.currentTimeMillis();ArrayList<Thread> threads = new ArrayList<Thread>();threads.add(philosopher1);threads.add(philosopher2);threads.add(philosopher3);threads.add(philosopher4);threads.add(philosopher5);philosopher2.start();philosopher4.start();philosopher1.start();philosopher3.start();philosopher5.start();for (Thread thread : threads) {try {thread.join();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println(System.currentTimeMillis() - startTime);}}
为了防止5位哲学家同时拿筷子,同时等或是同时放下。可以让哲学家2和4先。