-1

我对 Java 线程很陌生。尝试使用Java的同步概念来做死锁机制。这其中存在一些问题。我想知道我应该如何改进我的代码。我的目标是避免死锁

package threading;

import java.util.logging.Level;
import java.util.logging.Logger;


public class DiningPhilospherProblem {

  public static void main(String[] args)
  {
      Chopstick cs[] = new Chopstick [5];
      for(int i=0;i<5;i++)
      {
          cs[i] = new Chopstick();
      }


      new Thread(new Philospher("One", cs[4],cs[0]) ).start();
      new Thread(new Philospher("Two", cs[0],cs[1]) ).start();
      new Thread(new Philospher("Three", cs[1],cs[2]) ).start();
      new Thread(new Philospher("Four", cs[2],cs[3]) ).start();
      new Thread(new Philospher("Five", cs[3],cs[4]) ).start();
  }
}

class Philospher implements Runnable
{
    private static final int EATING_TIME = 8000;
    private static final int THINKING_TIME  = 10000;


    public enum State {
        EATING, THINKING, WAITING
    }

    Chopstick left, right;
    String name;
    State state;
    public Philospher(String name, Chopstick left,Chopstick right)
    {
        System.out.println(" Philospher "  + name + " is ready");
        this.name = name;
        this.left =left;
        this.right = right;
    }
    public void run()
    {
       for(int i =0; i< 10;i++){

                eat();

        }

        System.out.println("Succesfully finished: " +name);
    }
    public void eat()  // EDITED THIS FUNCTION
    {
        synchronized(left){
        try{


                while(right.isBeingUsed()){
                    System.out.println("Philospher " + name + " :  is waiting");
                    setPhilosopherState(Philospher.State.WAITING);
                    left.wait();
                }

                synchronized(right)
                {
                    left.setChopStickUsed(true);
                    right.setChopStickUsed(true);

                    System.out.println("Philospher " + name + " :  is eaitng");
                    setPhilosopherState(Philospher.State.EATING);

                    Thread.sleep(EATING_TIME);
                }
            }

        catch(InterruptedException e){}
        finally
        {
            left.setChopStickUsed(false);
            right.setChopStickUsed(false);
            left.notify();

        }
        }
        think();

    }

    public void think()
    {
        System.out.println("Philospher " + name + " :  is thinking");
        try 
        {
            setPhilosopherState(State.THINKING);
            Thread.sleep(THINKING_TIME);
        } 
        catch (InterruptedException ex) {
            Logger.getLogger(Philospher.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
     private void setPhilosopherState(State state){
        this.state = state;

        System.out.println("Setting state :  "+ state +", "+ name+";");
    }
}

class Chopstick
{
    boolean state_chopstick;

    public synchronized void  setChopStickUsed(boolean value)
    {
        state_chopstick = value;

    }
    public synchronized boolean isBeingUsed ()
    {
        return state_chopstick;
    }
}

编辑: eat()方法请查看

4

2 回答 2

1

除了 assylias 对您的直接问题的回答之外,还有一些关于改进逻辑的建议:

检查之间left.isBeingUsed()可能left.setChopStickUsed(true);有人已经抓住了筷子(这称为检查时间与使用时间的问题)。为确保不会发生这种情况,您需要使用适当的机制以仅允许一位哲学家访问筷子对象并原子地进行检查+抓取,例如将吃的逻辑替换为

boolean isEating = false;
if (left.grab()) {
  if (right grab) {
    // managed to grab both chopsticks
    isEating = true;
  } else {
    // only grabbed the left one
    left.release();
  }
} else {
  // could not grab the left one
}

if (isEating) {
  // TODO: chew, swallow
  left.release();
  right.release();
} else {
  // contemplate the cruelty of life
  think();
}

whereChopstick有以下方法:

public synchronized boolean grab()
{
  if (state_chopstick) {
    // already in use
    return false;
  }
  _state_chopstick = true;
  return true; // managed to grab it
}

public synchronized void release()
{
  state_chopstick = false;
}

这个想法是grab()检查筷子是否在使用如果不是同时抓住它这避免了检查时间/使用时间问题)

注意:上面的实现可能会导致活锁,所有哲学家同时抓住左边的筷子,然后找到正在使用的右边的筷子,松开左边的,思考并重复;因此从不吃东西。为了解决这个问题,您可以动态(例如随机)决定首先抓取哪个分叉

于 2012-05-25T10:58:03.133 回答
0

你得到一个IllegalMonitorException因为你没有持有对象waiteat锁(this)。你应该看看javadoc

你也不打电话notifynotifyAll所以你会一直等。

您可能打算think代替wait?

于 2012-05-25T09:59:26.563 回答