1

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

2 回答 2

8

这是直接的问题:

Consumer(PriorityBlockingQueue<Character> queue )
{
    queue = queue;  
}

这是一个无操作语句,将参数的值分配回自身。你要:

Consumer(PriorityBlockingQueue<Character> queue )
{
    this.queue = queue;  
}

一旦你解决了这个问题,你就会因为调用poll()(decalred in )而遇到潜在的问题,如果队列为空Queue,它将返回。null然后该空引用将被拆箱以将值分配给c变量(类型为char)。

使用take()(declared in BlockingQueue) 代替,这将阻塞。您可能还想指定超时。

于 2012-09-20T12:49:44.133 回答
3

Use take instead of pollpoll 可能返回 null。

JavaDoc#poll()

此队列的头部,如果此队列为空,则返回 null

用于put添加和采用get哪些阻塞方法。

于 2012-09-20T12:49:13.007 回答