一个有3个线程的程序,由Main主线程进入,生产者线程产生一个随机的整数。这个整数存在List中,再由消费者线程读取List数据,并显示。我写了代码,但是一直报lang.NullPointerException错误,看了半天没解决,请教哪位给解释下,谢谢!class Consumer implements Runnable {
Q q; Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
} @Override
public void run() {
while (true) {
q.get();
}
}
}class Producer implements Runnable {
Q q; Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
} @Override
public void run() {
while (true) {
q.put(new Random());
}
}class PC {
public static void main(String[] args) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control c to stop");
}
}class Q {
List l;
boolean valueset = false;
Object rand; synchronized Object get() {
if (!valueset)
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Got Random number in the List");
valueset = false;
notify();
Object temp = l.remove(0);
System.out.println(temp);
return temp;
} synchronized void put(Object rand) {
if (valueset)
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
this.rand = rand;
System.out.println("Put Random number in the List");
l.add(rand);
valueset = true;
notify();
}
}