我对 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()
方法请查看