0

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

 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) {

             }

        }

   }
}

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

它只适用于 1 个队列BlockingQueue queue = new LinkedBlockingQueue(5);

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

有人知道怎么修这个东西吗?我正在使用 netbeans IDE 7.3.1。

谢谢。

4

1 回答 1

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

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

for(int i=0; i<queue.length; i++){
    queue[i]=new LinkedBlockingQueue(); //change constructor as needed
}
于 2013-07-23T16:27:59.670 回答