我正在尝试生产者/消费者问题,但我不知道为什么要 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)