如图所示,桌上摆着五支(不是五双)筷子。哲学家的状态可能是“思考”和“饥饿”。如果饥饿,哲学家将拿起他两边的筷子并进餐一段时间。进餐结束,哲学家就会放回筷子。
package com.my.diningphilosopherscondition; import java.util.concurrent.locks.ReentrantLock; public class DiningPhilosophers { public static void main(String[] args) throws InterruptedException { final Philosopher[] philosophers = new Philosopher[5]; final ReentrantLock table = new ReentrantLock(); for (int i = 0; i < 5; ++i) philosophers[i] = new Philosopher(table); for (int i = 0; i < 5; ++i) { philosophers[i].setLeft(philosophers[(i + 4) % 5]); philosophers[i].setRight(philosophers[(i + 1) % 5]); philosophers[i].start(); } class CountingThread extends Thread { @SuppressWarnings("static-access") public void run() { while (!interrupted()) { try { currentThread().sleep(100); } catch (InterruptedException e) { } for (int i = 0; i < 5; ++i){ System.out.print("\r"+i+"号哲学家: " + (philosophers[i].isEating()?"正在进餐":"思考中...")); } System.out.println("\r=================="); System.out.flush(); } } } CountingThread t3 = new CountingThread(); t3.start(); for (int i = 0; i < 5; ++i) philosophers[i].join(); t3.interrupt(); } }
package com.my.diningphilosopherscondition; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import java.util.Random; class Philosopher extends Thread { private boolean eating; private Philosopher left; private Philosopher right; private ReentrantLock table; private Condition condition; private Random random; private int thinkCount; public Philosopher(ReentrantLock table) { eating = false; this.table = table; condition = table.newCondition(); random = new Random(); } public void setLeft(Philosopher left) { this.left = left; } public void setRight(Philosopher right) { this.right = right; } public void run() { try { while (true) { think(); eat(); } } catch (InterruptedException e) { } } private void think() throws InterruptedException { table.lock(); try { eating = false; left.condition.signal(); right.condition.signal(); } finally { table.unlock(); } ++thinkCount; if (thinkCount % 10 == 0) System.out.println("Philosopher " + this + " has thought " + thinkCount + " times"); Thread.sleep(random.nextInt(3000)); } private void eat() throws InterruptedException { table.lock(); try { while (left.eating || right.eating) condition.await(); eating = true; } finally { table.unlock(); } Thread.sleep(random.nextInt(3000)); } public boolean isEating() { return eating; } public void setEating(boolean eating) { this.eating = eating; } }
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于