创建一个blockqueue数组

时间:2013-07-23 16:26:36

标签: java multithreading blockingqueue

我正在实现多线程,并希望能够从主要的每个线程发送/接收消息。所以我试图使用以下代码为每个线程设置阻塞队列:

 public static void main(String args[]) throws Exception {
    int deviceCount = 5;
    devices = new DeviceThread[deviceCount];
    BlockingQueue<String>[] queue = new LinkedBlockingQueue[5];

    for (int j = 0; j<deviceCount; j++){
        device = dlist.getDevice(); //get device from a device list
        devices[j] = new DeviceThread(queue[j], device.deviceIP, port, device.deviceID, device.password);
        queue[j].put("quit");
    }
}


public class DeviceThread implements Runnable {
    Thread t;
    String ipAddr;
    int port;
    int deviceID;
    String device;
    String password;
    BlockingQueue<String> queue;


    DeviceThread(BlockingQueue<String> q, String ipAddr, int port, int deviceID, String password) {

        this.queue=q;
        this.ipAddr = ipAddr;
        this.port = port;
        this.deviceID = deviceID;
        this.password = password;
        device = "device"+this.deviceID;
        t = new Thread(this, device);
        System.out.println("device created: "+ t);
        t.start(); // Start the thread
    }

    public void run() {
        while(true){
             System.out.println(device + " outputs: ");
             try{
                 Thread.sleep(50);
                 String input =null;
                 input = queue.take();
                 System.out.println(device +"queue : "+ input);
             }catch (InterruptedException a) {

             }

        }

   }
}

编译的代码但在运行时它在行queue[j].put("quit");上给我一个NullPointerException

只使用了1个队列BlockingQueue queue = new LinkedBlockingQueue(5);

我相信它是因为数组未正确初始化,我尝试将其声明为BlockingQueue[] queue = new LinkedBlockingQueue10;但它给了我“;是预期的”

任何人都知道如何解决这个问题?我正在使用netbeans IDE 7.3.1。

感谢。

1 个答案:

答案 0 :(得分:3)

 BlockingQueue<String>[] queue = new LinkedBlockingQueue[5];

创建一个空引用数组。你需要实际初始化每一个:

for(int i=0; i<queue.length; i++){
    queue[i]=new LinkedBlockingQueue(); //change constructor as needed
}
相关问题