声明LinkedBlockingQueue <string> </string>时获取NullPointer异常

时间:2013-07-23 04:11:14

标签: java nullpointerexception queue

这是我的代码。我在构造函数的最后一行得到了Null Pointer Exception(workerQueue [i] = new LinkedBlockingQueue(100);):

public class QueueThreadPool {

  private BlockingQueue<String>[] workerQueue;
  private Thread[] workerThreads;
  private int numQueues;
  private int numThreads;

public QueueThreadPool(int numThreads, int numQueues) {
    this.numQueues = numQueues;
    this.numThreads = numThreads;

    for(int i=1; i<=numQueues; i++){
        workerQueue[i] = new LinkedBlockingQueue<String>(100);
    }
}
public static void main(String args[]){
    System.out.println("Start...");
    new QueueThreadPool(50, 11);
    System.out.println("End...");
}

请帮忙! 谢谢!

3 个答案:

答案 0 :(得分:2)

未实例化数组workerQueue,您需要这样做。

private BlockingQueue<String>[] workerQueue;

workerQueueBlockingQueue<String>[]类型的引用,而不是对象。

但您也无法创建BlockingQueue<String> 的通用数组。而不是创建List BlockingQueue<String>。前 -

private List<BlockingQueue<String>> workerQueue= new ArrayList<>();

您还可以在构造函数中创建列表Object。

private List<BlockingQueue<String>> workerQueue= new ArrayList<>();
public QueueThreadPool(int numThreads, int numQueues) {
    this.workerQueue = new ArrayList<>(numQueues);  // <-- initialize the field.
    this.numQueues = numQueues;
    this.numThreads = numThreads;
    ...

答案 1 :(得分:0)

您尚未初始化workerThreads。您必须执行workerQueue= new BlockingQueue<String>[numQueues];

之类的操作

答案 2 :(得分:0)

代码中有两个问题:字段需要初始化,循环应该从0到数组大小 - 1.这是固定代码的样子:

public class QueueThreadPool {

  private BlockingQueue<String>[] workerQueue;
  private Thread[] workerThreads;
  private int numQueues;
  private int numThreads;

public QueueThreadPool(int numThreads, int numQueues) {
    this.workerQueue = new BlockingQueue<String>[numQueues]  // <-- You need to initialize the field.
    this.numQueues = numQueues;
    this.numThreads = numThreads;

    for(int i=0; i < numQueues; i++){  // <-- Indexing into arrays goes from 0 to size-1     (inclusive).
        workerQueue[i] = new LinkedBlockingQueue<String>(100);
    }
}