我正在尝试一个生产者/消费者问题,但是我不知道为什么要进入 java.lang.NullPointerException消费者内部。
java.lang.NullPointerException
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; }
那是一条无操作的语句,将参数的值赋给它自己。你要:
Consumer(PriorityBlockingQueue<Character> queue ) { this.queue = queue; }
一旦你定,你会 再 有一个潜在的问题,因为调用poll()(decalred中Queue),这将返回null如果队列为空。然后,该空引用将被取消装箱,以将值分配给c变量(类型char)。
poll()
Queue
null
c
char
请改用take()(在中声明BlockingQueue),这将阻止。您可能还需要指定一个超时。
take()
BlockingQueue