Java多线程,哲学家就餐问题解决方案

121 阅读1分钟

main方法

package com.itheima;

import com.itheima.pojo.Chopsticks;
import com.itheima.pojo.People;

public class App {
    public static void main(String[] args) {
        Chopsticks ch1 = new Chopsticks("1号筷子");
        Chopsticks ch2 = new Chopsticks("2号筷子");
        Chopsticks ch3 = new Chopsticks("3号筷子");
        Chopsticks ch4 = new Chopsticks("4号筷子");
        Chopsticks ch5 = new Chopsticks("5号筷子");

        People peo1 = new People("哲学家1",ch1.getName(),ch2.getName(),1); //添加一个左撇子 让他从左拿 其他人都从右拿
        People peo2 = new People("哲学家2",ch2.getName(),ch3.getName(),0);
        People peo3 = new People("哲学家3",ch3.getName(),ch4.getName(),0);
        People peo4 = new People("哲学家4",ch4.getName(),ch5.getName(),0);
        People peo5 = new People("哲学家5",ch5.getName(),ch1.getName(),0);
        peo1.start();
        peo2.start();
        peo3.start();
        peo4.start();
        peo5.start();
    }

}

线程类

package com.itheima.pojo;

import sun.dc.pr.PRError;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class People extends Thread{
   private String name;
   private String left;
   private String right;
   private int index; //添加index属性

    public People(String name, String left, String right,int index) {
        this.name = name;
        this.left = left;
        this.right = right;
        this.index = index;
    }

  public synchronized void run(){
        if(this.index == 1){ //当index为1时先从左拿筷子再从右拿
            synchronized (left){
                System.out.println(this.name + "拿起了" + this.left);
                synchronized (right){
                    System.out.println(this.name + "拿起了" +this.right);
                    this.eat();
                }
            }
        }else {//否则先从右拿再从左拿
            synchronized (right){
                System.out.println(this.name + "拿起了" + this.left);
                synchronized (left){
                    System.out.println(this.name + "拿起了" +this.right);
                    this.eat();
                }
            }
        }
  }
  public  void eat(){
          System.out.println(this.name + "开始吃饭");
          try {
              Thread.sleep(1000);
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
          System.out.println(this.name + "花一秒钟吃完了");
  }

}

筷子类

package com.itheima.pojo;

public class Chopsticks {
    private String name;

    public Chopsticks(String name) {
        this.name = name;
    }

    public Chopsticks() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Chopsticks{" +
                "name='" + name + ''' +
                '}';
    }
}