java 多线程 避免死锁 哲学家就餐问题
2017-11-30 09:30
337 查看
源代码如下:
public class Concurrence implements Runnable{ private chick pre; private chick last; private int index; public Concurrence(chick pre, chick last, int index) { this.pre = pre; this.last = last; this.index = index; } public void eating(){ System.out.println("pre"+index+":eating......"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } public void thinking(){ System.out.println("pre"+index+":thinking......"); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void run() { while (true){ if(pre.isSatuts()){ synchronized (pre) { pre.setSatuts(false); if (last.isSatuts()) { synchronized (last) { last.setSatuts(false); eating(); pre.setSatuts(true); last.setSatuts(true); last.notifyAll(); } } else { thinking(); } thinking(); try { pre.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } }else { thinking(); } thinking(); } } } class chick{ private int index; private boolean satuts=true; public chick(int index,boolean satuts) { this.index = index; this.satuts = satuts; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public synchronized boolean isSatuts() { return satuts; } public synchronized void setSatuts(boolean satuts) { this.satuts = satuts; } } public static void main(String[] args) throws InterruptedException { chick c1=new chick(1,true); chick c2=new chick(2,true); chick c3=new chick(3,true); chick c4=new chick(4,true); chick c5=new chick(5,true); Concurrence con1=new Concurrence(c1,c2,1); Concurrence con2=new Concurrence(c2,c3,2); Concurrence con3=new Concurrence(c3,c4,3); Concurrence con4=new Concurrence(c4,c5,4); Concurrence con5=new Concurrence(c5,c1,5); new Thread(con1).start(); new Thread(con2).start(); new Thread(con3).start(); new Thread(con4).start(); new Thread(con5).start(); }
相关文章推荐
- java 多线程 死锁 哲学家就餐问题
- Thking in Java---从哲学家就餐问题看死锁现象
- 【面试系列】哲学家就餐问题(3个)--多线程,防死锁
- Java多线程,哲学家就餐问题
- JAVA多线程学习--哲学家就餐问题
- 死锁原因,解决,避免方法及哲学家就餐问题
- java多线程--哲学家就餐问题
- 哲学家就餐问题中的JAVA多线程学习
- JAVA多线程学习--哲学家就餐问题
- JAVA多线程学习--哲学家就餐问题
- 【JAVA多线程问题之死锁】
- linux下 多线程编程 哲学家就餐问题
- JavaSE第一百零四讲:哲学家就餐问题、死锁与使用wait及notify方法实现线程之间的相互通信
- java例程练习(多线程[死锁问题])
- 如何防止哲学家就餐问题而引起的死锁
- 多线程之哲学家就餐问题
- apue学习第十八天——从哲学家就餐问题看死锁
- 多线程--哲学家就餐问题
- Java笔记3 多线程<1>线程概述、多线程的创建、多线程的安全问题、静态同步函数的锁、死锁
- 黑马程序员:Java基础——多线程的死锁问题