0

这是我的代码。我在构造函数的最后一行得到空指针异常(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...");
}

请帮忙!谢谢!!

4

3 回答 3

2

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

private BlockingQueue<String>[] workerQueue;

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

但你也不能创建一个通用数组BlockingQueue<String>。而不是创建一个Listof BlockingQueue<String>。前任 -

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

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

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;
    ...
于 2013-07-23T04:14:08.020 回答
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);
    }
}
于 2013-07-23T04:18:50.110 回答
0

你还没有初始化workerThreads。你必须做类似的事情workerQueue= new BlockingQueue<String>[numQueues];

于 2013-07-23T04:14:54.743 回答