兩個(gè)人吃飯,但只有一個(gè)勺子和叉子,只有同時(shí)獲得勺子和叉子才能吃到飯。兩個(gè)人是兩個(gè)線程,線程的run方法是獲取勺子和叉子并eat。eat方法加了synchronized 但為什么還是不能互斥,兩個(gè)人不是同一時(shí)刻只能有一個(gè)人吃么?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();
}
}為什么會(huì)出現(xiàn)下面的情況:同一時(shí)刻不是只能有一個(gè)人進(jìn)入臨界區(qū)么,怎么Tom和Jerry為什么會(huì)同時(shí)進(jìn)入?大佬們幫幫忙,想不明白。。。。
java多線程,類似哲學(xué)家進(jìn)餐問題
ibeautiful
2019-04-19 13:15:49