import java.util.concurrent.*; import java.util.concurrent.locks.*; class Philo implements Runnable { int no=0; private Lock lock=null; Philo(int num) { this.lock=new ReentrantLock(); this.no = num; } public void run() { while(takeChopstics()) { eatDinner(); putChopstics(); Thread.yield(); } } Boolean takeChopstics() { System.out.println("Philosophier" + this.no +"Starting to get chopstics"); lock.lock(); if(!Dinner.sticks[no]&&!Dinner.sticks[(no+1)%5]) { Dinner.sticks[no]=true; Dinner.sticks[(no+1)%5]=true; lock.unlock(); return true; } else{ lock.unlock(); return false; } } void eatDinner() { System.out.println("Philosophier" + this.no +"eating..."); try{ Thread.sleep(5000); }catch(InterruptedException e){ System.out.println(e.toString()); } } void putChopstics() { lock.lock(); Dinner.sticks[no] = false; Dinner.sticks[(no+1)%5] = false; lock.unlock(); System.out.println("Philosophier" + this.no +"Puting chopstics"); } } public class Dinner{ static Boolean[] sticks = {false, false, false, false, false}; public static void main(String[] args) { for(int i=0; i<5; i++) new Thread(new Philo(i)).start(); } }
哲学家进餐---并发编程
最新推荐文章于 2021-12-15 14:41:42 发布