📄 diding.java
字号:
package threadPhilosofor;
class ChopStick { //筷子类
boolean available;
ChopStick() {
available=true; //可以拿起
}
public synchronized void takeup() { //拿起动作
while(!available) {
try {
wait();
System.out.println("哲学家等待另一根筷子");
} catch(InterruptedException e) { }
}
available=false;
}
public synchronized void putdown() { //放下动作
available=true;
notify();
}
}
class Philosopher extends Thread { //哲学家类
ChopStick left, right;
int philo_num; //哲学家编号
Philosopher (int num, ChopStick c1, ChopStick c2) {
philo_num = num;
left = c1;
right = c2;
setDaemon(true); //此函数设true时,关闭主线程,子线程也跟着关闭
//否则,关闭主线程,子线程继续执行
}
public void eat() {
left.takeup();
right.takeup();
System.out.println("哲学家 " + (philo_num + 1) + " 正在进餐");
}
public void think() {
left.putdown();
right.putdown();
System.out.println("哲学家 " + (philo_num + 1) + " 正在思考");
}
public void run() {
while(true) {
eat();
try {
sleep(2000); //吃的时间是2秒
}
catch (InterruptedException e) {}
think();
try {
sleep(2000); //思考的时间也是2秒
}
catch (InterruptedException e) {}
}
}
}
public class DiDing {
static ChopStick[] chopsticks = new ChopStick[5];
static Philosopher[] philos = new Philosopher[5];
public static void main(String args[]) {
for (int i = 0; i < 5; i ++ ) {
chopsticks[i] = new ChopStick();
}
for (int i = 0; i < 5; i ++ ) {
philos[i] = new Philosopher(i, chopsticks[i], chopsticks[(i + 1) % 5]);
}
for (int i = 0; i < 5; i ++) {
philos[i].start();
}
try
{
System.in.read(); //wait until Enter is pressed
for (int i = 0; i < 5; i ++) {
philos[i].interrupt();
}
}
catch(Exception e)
{ }
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -