两个人吃饭,但只有一个勺子和叉子,只有同时获得勺子和叉子才能吃到饭。两个人是两个线程,线程的run方法是获取勺子和叉子并eat。eat方法加了synchronized 但为什么还是不能互斥,两个人不是同一时刻只能有一个人吃么?public class Tool {
private final String name;
public Tool(String name){
this.name=name;
}
}public class EaterThread extends Thread{
private final Tool leftHand;
private final Tool rightHand;
private String personName;
public EaterThread(String personName,Tool leftHand,Tool rightHand) {
this.leftHand=leftHand;
this.rightHand=rightHand;
this.personName=personName;
}
public synchronized void eat(){
System.out.println(this.personName+"拿起"+this.leftHand);
System.out.println(this.personName+"拿起"+this.rightHand);
System.out.println(this.personName+"吃饭");
System.out.println(this.personName+"放下"+this.leftHand);
System.out.println(this.personName+"放下"+this.rightHand);
}
public void run(){
while(true){
this.eat();
try {
Thread.sleep(1000);
} catch (Exception e) {}
}
}
}public class Main {
public static void main(String[] args) {
Tool spoon=new Tool("spoon");
Tool fork=new Tool("fork");
new EaterThread("Tom", spoon, fork).start();
new EaterThread("Jerry", spoon, fork).start();
}
}为什么会出现下面的情况:同一时刻不是只能有一个人进入临界区么,怎么Tom和Jerry为什么会同时进入?大佬们帮帮忙,想不明白。。。。
添加回答
举报
0/150
提交
取消