您的位置:首页 > 其它

哲学家吃饭问题(资源加锁和超时释放)

2017-08-22 10:15 239 查看
public class Resourcelocking extends Thread{

private static int[] chopstick = { 1, 1, 1, 1, 1 };
private int i;

public Resourcelocking(int i) {
this.i = i;
}

@Override
public void run() {

//synchronized (chopstick) {  //若注释此行,打开下行,不同步,5个per只拿到左筷子
{
eat(this.getName()); //得到线程的名字

think(this.getName());
}

}

private void think(String name) {
//在思考的时候把筷子置为可用
chopstick[i] = 1;
chopstick[(i + 1) % 5] = 1;
System.out.println("per"+name+" is thinking...");

}

private void eat(String string) {

while (true) {

if (chopstick[i] != 0) {//说明当前现这根筷子没有被占用
chopstick[i]--;
System.out.println("per" + this.getName()
+ " got left chopstick.");
break;
}
}

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

//拿到左筷子后开始拿右筷子
while (true) {
if (chopstick[(i + 1) % 5] != 0) {
chopstick[(i + 1) % 5]--;
System.out.println("per" + this.getName()
+ " got right chopstick.");
break;
}

}
System.out.println("per" + string + " is eating...");
}
}


public class Timeoutrelease extends Thread{
private static int[] chopstick = {1,1,1,1,1};
private int i;
private int n = 5;

public Timeoutrelease(int i) {
this.i = i;
}

@Override
public void run() {

//拿左筷子
synchronized (chopstick) {
while (chopstick[i] == 0) {
try {
chopstick.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

chopstick[i]--;
System.out.println("per" + this.getName()
+ " got left chopstick.");
chopstick.notify();
}

// 睡一下产生死锁
try {
Thread.sleep((long) (Math.random()*1000));
} catch (InterruptedException e) {
e.printStackTrace();
}

//拿右筷子
synchronized (chopstick) {
while (chopstick[(i + 1) % n] == 0) {
try {
chopstick.wait(3*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally{
System.out.println(this.getName()+" waited 3s ,free left chopstick");
chopstick[i] ++;
}
}

chopstick[(i + 1) % n]--;
System.out.println("per" + this.getName()
+ " got right chopstick.");

System.out.println("per" + this.getName() + " is eating...");

chopstick[i]++;
chopstick[(i + 1) % n]++;
System.out.println("per"+this.getName()+" is thinking...");

chopstick.notify();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: