public class Philosophers implements Runnable { private Semaphore leftFork; private Semaphore rightknife; private int id; public Philosophers(int id, Semaphore leftFork, Semaphore rightknife) { this.id = id; this.leftFork = leftFork; this.rightknife = rightknife; } public void run() { try { //思考 System.out.println("哲学家" + id + "正在思考"); Thread.sleep((long) (Math.random() * 10000)); //进餐 System.out.println("哲学家" + id + "饿了,开始进餐"); leftFork.acquire(); System.out.println("哲学家" + id + "拿起左边的叉子"); rightknife.acquire(); System.out.println("哲学家" + id + "拿起右边的刀子"); Thread.sleep((long) (Math.random() * 10000)); System.out.println("哲学家" + id + "进餐完毕,放下叉子"); //释放叉子 rightknife.release(); System.out.println("哲学家" + id + "放下右边的刀子"); leftFork.release(); System.out.println("哲学家" + id + "放下左边的叉子"); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { int N = 5; //哲学家数量 Semaphore[] forks = new Semaphore[N]; for (int i = 0; i < N; i++) { forks[i] = new Semaphore(1); } for (int i = 0; i < N; i++) { new Thread(new Philosophers(i, forks[i], forks[(i + 1) % N])).start(); } } }优化上述代码避免发生死锁并为各行代码添加注释
时间: 2023-12-22 20:03:12 浏览: 23
为了避免死锁,需要对程序中的资源竞争进行优化。下面是对代码进行的修改:
```
public class Philosophers implements Runnable {
private Semaphore leftFork;
private Semaphore rightFork; // 修改成叉子的信号量
private int id;
public Philosophers(int id, Semaphore leftFork, Semaphore rightFork) {
this.id = id;
this.leftFork = leftFork;
this.rightFork = rightFork;
}
public void run() {
try {
//思考
System.out.println("哲学家" + id + "正在思考");
Thread.sleep((long) (Math.random() * 10000));
//进餐
System.out.println("哲学家" + id + "饿了,开始进餐");
// 判断左右叉子,只有当两个叉子都可用时才能取到叉子
if (id % 2 == 0) {
leftFork.acquire();
System.out.println("哲学家" + id + "拿起左边的叉子");
rightFork.acquire();
System.out.println("哲学家" + id + "拿起右边的叉子");
} else {
rightFork.acquire();
System.out.println("哲学家" + id + "拿起右边的叉子");
leftFork.acquire();
System.out.println("哲学家" + id + "拿起左边的叉子");
}
Thread.sleep((long) (Math.random() * 10000));
System.out.println("哲学家" + id + "进餐完毕,放下叉子");
//释放叉子
rightFork.release();
System.out.println("哲学家" + id + "放下右边的叉子");
leftFork.release();
System.out.println("哲学家" + id + "放下左边的叉子");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
int N = 5; //哲学家数量
Semaphore[] forks = new Semaphore[N];
for (int i = 0; i < N; i++) {
forks[i] = new Semaphore(1);
}
for (int i = 0; i < N; i++) {
new Thread(new Philosophers(i, forks[i], forks[(i + 1) % N])).start();
}
}
}
```
注释如下:
1. 将 rightknife 修改为 rightFork,以更好地反映代码含义。
2. 在进餐前,对哲学家编号进行判断,偶数编号的哲学家先取左边的叉子,奇数编号的哲学家先取右边的叉子。
3. 注释相关代码,方便理解和调试。