我在Consumer中收到NullPointerException [英] I am getting NullPointerException inside Consumer
问题描述
我正在尝试一个生产者/消费者问题,但是我不知道为什么我在消费者中得到了java.lang.NullPointerException
.
I was trying a Producer/Consumer Problem, but I don't know why I am getting java.lang.NullPointerException
inside the Consumer.
package com ;
import java.util.concurrent.PriorityBlockingQueue;
public class Producer extends CommonClass implements Runnable {
private int producerNum;
Producer(PriorityBlockingQueue<Character> queue) {
queue = queue;
}
public void run() {
char ch;
for (ch = 'a'; ch <= 'z'; ch++) {
queue.add(ch);
System.out.println("Producer" + producerNum + "produced :" + ch);
try {
Thread.sleep((int) (Math.random() * 300));
} catch (InterruptedException e) {
System.out.println("Error");
}
}
}
}
这是我的消费者类
package com ;
import java.util.concurrent.PriorityBlockingQueue;
public class Consumer extends CommonClass implements Runnable {
private int consumerNum;
Consumer(PriorityBlockingQueue<Character> queue )
{
queue = queue;
}
public void run() {
char c;
for (int i = 0; i < 27; i++) {
c = queue.poll();
System.out.println("Consumer" + consumerNum + "consumed:" + c);
try {
Thread.sleep((int) (Math.random() * 300));
} catch (InterruptedException e) {
System.out.println("Error");
}
}
}
}
package com ;
import java.util.concurrent.PriorityBlockingQueue;
public class CommonClass {
PriorityBlockingQueue<Character> queue = new PriorityBlockingQueue<Character>();
}
package com ;
import java.util.concurrent.PriorityBlockingQueue;
public class SyncTest {
public static void main(String[] args) {
PriorityBlockingQueue<Character> queue = new PriorityBlockingQueue<Character>();
Producer p1 = new Producer(queue);
Thread t1 = new Thread(p1);
t1.start();
Consumer c1 = new Consumer(queue);
Thread ct1 = new Thread(c1);
ct1.start();
}
}
这是我得到的例外:
Exception in thread "Thread-1" java.lang.NullPointerException
at com.Consumer.run(Consumer.java:18)
at java.lang.Thread.run(Unknown Source)
推荐答案
这是当前的问题:
Consumer(PriorityBlockingQueue<Character> queue )
{
queue = queue;
}
这是一个无操作语句,将参数的值分配回给自己.您想要:
That's a no-op statement, assigning the parameter's value back to itself. You want:
Consumer(PriorityBlockingQueue<Character> queue )
{
this.queue = queue;
}
解决此问题后,您将然后存在潜在问题,原因是调用了poll()
(在Queue
中被拒绝),如果队列为空,它将返回null
.然后,该空引用将被取消装箱,以将值分配给c
变量(类型为char
).
Once you've fixed that, you'll then have a potential problem due to calling poll()
(decalred in Queue
), which will return null
if the queue is empty. That null reference will then be unboxed to assign the value to the c
variable (of type char
).
使用take()
(在BlockingQueue
中声明)代替,它将阻塞.您可能还需要指定一个超时时间.
Use take()
(declared in BlockingQueue
) instead, which will block. You may want to specify a timeout, too.
这篇关于我在Consumer中收到NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!