我正在尝试为丁宁哲学家实施一个解决方案。不确定我是否正确行事。我的程序没有崩溃,但我在输出中得到红色文本,但没有错误代码。
错误示例:
at(package_name).Phil.getrightFork(Phil.java:70) 第70行和第46行之间的错误替代(这是调用getrightFork的行)
我已经使用getleftFork交换getrightFork,但它总是选择rightFork作为错误
这是我正在使用的代码: 自定义信号量:
public class Semaphore {
public int value= 0 ;
public Semaphore(int value) {
this.value = value;
}
public synchronized void up() { //notify must be syncrhonized
value++;
if (value > 0){
this.notifyAll();
}
}
public synchronized void down() throws InterruptedException {
while (value <= 0){//Check if resource is avaiable, if not WAIT.
this.wait();
}
value--; // Value is no longer negative
}}
主:
public class main {
private static final int N = 10000;
public static void main(String[] args) throws InterruptedException{
Phil[] phils = new Phil[N];
Semaphore[] forks = new Semaphore[N];
for (int i=0;i<N;i++){
forks[i] = new Semaphore(1);
phils[i] = new Phil(i, forks, N);
phils[i].start();
}
for (int i=0;i<N;i++){
phils[i].join();
}
}}
菲尔班:
public class Phil extends Thread {
Semaphore fork[];
int phil, total, left, right;
boolean leftFork = false, rightFork = false;
public Phil(int spot ,Semaphore[] s, int N){
phil = spot;
left = spot;
fork = s;
switch(spot){
case 0:
right = N-1;
break;
default:
right = spot - 1;
break;
}
}
public void run(){
System.out.println("I am Phil " + phil + " my left fork is " + left + " my right fork is " + right);
while(true){
try {
if (phil%2 == 0){
Thread.sleep(10); // Let the odd Phils eat first
}
getrightFork();
if (rightFork){
getleftFork();
}
if (leftFork && rightFork){
eat();
retleftFork();
retrightFork();
}
Thread.sleep(10);
} catch (InterruptedException ex) {
}
}
}
void getleftFork() throws InterruptedException{
fork[left].down();
//System.out.println("I got my left fork!");
leftFork = true;
}
void getrightFork() throws InterruptedException{
fork[right].down();
//System.out.println("I got my right fork!");
rightFork = true;
}
void retleftFork(){
fork[left].up();
leftFork = false;
}
void retrightFork(){
fork[right].up();
rightFork = false;
}
void eat(){
System.out.println("Phil:" + phil + " ate");
}}
答案 0 :(得分:1)
您正在获得NullPointerException
。您尝试访问的数组中的元素是null
。
这是因为您在整个阵列完成之前start
Phil
...
Phil[] phils = new Phil[N];
Semaphore[] forks = new Semaphore[N];
for (int i = 0; i < N; i++) {
forks[i] = new Semaphore(1);
phils[i] = new Phil(i, forks, N);
// Phil is starting, but how many phils are there??
phil.start();
}
相反,首先尝试填充数组,然后在单独的循环中启动它们......
Phil[] phils = new Phil[N];
Semaphore[] forks = new Semaphore[N];
for (int i = 0; i < N; i++) {
forks[i] = new Semaphore(1);
phils[i] = new Phil(i, forks, N);
}
for (Phil phil : phils) {
phil.start();
}
for (int i = 0; i < N; i++) {
phils[i].join();
}
如果解决方案要求Phil
在创建后立即启动,那么您需要更改检查代码以处理下一个元素可能为null