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();
}
}
}