gpt4 book ai didi

java - 需要有关 Java 生产者消费者问题 NullPointerException 的帮助

转载 作者:行者123 更新时间:2023-11-30 07:37:26 26 4
gpt4 key购买 nike

这是我的代码:

package test;

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

class Data{
int ar[]=new int[50];
int ptr;

Data()
{
for(int i=0;i<50;i++)
ar[i]=0;
ptr=0;
}

public int produce()
{
if(this.ptr<50)
{
this.ar[this.ptr]=1;
this.ptr++;
return this.ptr;
}
else return -1;
}

public int consume()
{
if(this.ptr>0)
{
this.ar[this.ptr]=0;
this.ptr--;
return this.ptr;
}
else
return -1;

}
}
class Prod implements Runnable{

private Main m;

Prod(Main mm)
{
m=mm;
}

public void run()
{

int r = m.d.produce();
if (r != -1) {
System.out.println("Produced, total elements: " + r);
} else
{
try {
wait();
}
catch (InterruptedException ex) {
Logger.getLogger(Prod.class.getName()).log(Level.SEVERE, null, ex);
}
}

}
}

class Cons implements Runnable{

private Main m;

Cons(Main mm)
{
m=mm;
}
public void run()
{
int r=m.d.consume();
if(r!=-1)
System.out.println("Consumed, total elements: " + r);
else
{
try {
wait();
}
catch (InterruptedException ex) {
Logger.getLogger(Prod.class.getName()).log(Level.SEVERE, null, ex);
}

}
notify();
}

}
public class Main{
Data d;
public static void main(String s[]) throws InterruptedException{
Main m = new Main();
Prod p = new Prod(m);
Cons c = new Cons(m);
new Thread(p).start();
new Thread(c).start();

}
}

出现以下错误:

Exception in thread "Thread-0" Exception in thread "Thread-1" java.lang.NullPointerException at test.Cons.run(Main.java:84) at java.lang.Thread.run(Thread.java:619) java.lang.NullPointerException at test.Prod.run(Main.java:58) at java.lang.Thread.run(Thread.java:619)

我是 Java 新手。任何帮助将不胜感激。

最佳答案

我会看下面几行:

public void run()
{
int r=m.d.consume();

我没有看到 m.d 在哪里被赋予了 new Data() 的实例

我会向 Main 添加一个构造函数,它创建一个 Data 实例并将其分配给 d。

public class Main{
Data d;
public static void main(String s[]) throws InterruptedException{
Main m = new Main();
Prod p = new Prod(m);
Cons c = new Cons(m);
new Thread(p).start();
new Thread(c).start();

}

== 添加 ==

public Main(){
d = new Data();
}

== 添加了 ==

}

关于java - 需要有关 Java 生产者消费者问题 NullPointerException 的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2653786/

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