gpt4 book ai didi

java - "Dining Philosophers"在Java中使用Future

转载 作者:行者123 更新时间:2023-12-02 06:29:25 26 4
gpt4 key购买 nike

我正在尝试使用 Java 中的 Future 来解决哲学家问题。

 public class Philo implements Callable<PhiloStatus> {

private PhiloStatus status;
private Philo leftPhilo;
private Philo rightPhilo;

private String name;

public Philo(String name) {
status = PhiloStatus.THINKING;

this.name =name;
}



public void setLeftPhilo(Philo leftPhilo) {
this.leftPhilo = leftPhilo;
}

enter code here

public void setRightPhilo(Philo rightPhilo) {
this.rightPhilo = rightPhilo;
}



@Override
public PhiloStatus call() throws Exception {

if (leftPhilo.getStatus() == PhiloStatus.THINKING
&& rightPhilo.getStatus() == PhiloStatus.THINKING) {

this.status =PhiloStatus.DINING;
System.out.println("Dininig "+this);
return PhiloStatus.DINING;

}

this.status =PhiloStatus.THINKING;
System.out.println("Thinking "+this);
return PhiloStatus.THINKING;
}

public PhiloStatus getStatus() {

return status;

}

@Override
public String toString() {
// TODO Auto-generated method stub
return name;
}

}

程序的起点

public class Start {

/**
* @param args
*/
public static void main(String[] args) {


ExecutorService executorService = Executors.newFixedThreadPool(5);
Philo[] philosophers = new Philo[5];


for (int i = 0; i < 5; ++i)
philosophers[i] = new Philo(""+i);
for (int i = 0; i < 5; ++i) {
philosophers[i].setLeftPhilo(philosophers[(i + 4) % 5]);
philosophers[i].setRightPhilo(philosophers[(i + 1) % 5]);

executorService.submit( philosophers[i]);

}



}

}

但是似乎一旦 Callable 完成执行,它就会返回相同的结果。

我现在怀疑使用Future可能无法解决这个问题?

有人可以解释一下吗?

最佳答案

class Philo implements Runnable{

@Override
public void run(){
while(true){

if(Thread.interrupted()){
break;
}

//dining logic
}

}
}

解决方案可以是一个循环,一直执行到有人打断Philosopher为止。

关于java - "Dining Philosophers"在Java中使用Future,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20215864/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com