qq_41235711 2019-04-27 20:37 采纳率: 66.7%
浏览 542
已采纳

java多线程,类似哲学家进餐问题

两个人吃饭,但只有一个勺子和叉子,只有同时获得勺子和叉子才能吃到饭。
两个人是两个线程,线程的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为什么会同时进入?
大佬们帮帮忙,想不明白。。。。

  • 写回答

2条回答 默认 最新

  • 毕小宝 博客专家认证 2019-04-28 09:14
    关注

    加锁的位置换一下,

      public  void eat(){
               synchronized(EaterThread.class){
    
                    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);        
                                    }
        }
    
    

    使用相同的锁对象。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入