您的位置:首页 > 编程语言 > Java开发

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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息