私は生産者/消費者問題を試みていましたが、なぜ私が 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)