2013-07-23 3 views
0

Я реализую многопоточность и хочу иметь возможность отправлять/получать сообщения в/из каждого потока из основного. Так что я пытаюсь настроить блокирование очереди для каждого потока с помощью следующего кода:Создание массива 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) { 

      } 

     } 

    } 
} 

код компилируется, но во время выполнения он дает мне NullPointerException на линии queue[j].put("quit");

он работал только с 1 очереди BlockingQueue queue = new LinkedBlockingQueue(5);

Я считаю его потому, что массив Isnt инициализирован правильно, я попытался объявить его как BlockingQueue[] queue = new LinkedBlockingQueue10;, но это дает мне «как ожидается,»

кто знает, как это исправить? Я использую netbeans IDE 7.3.1.

спасибо.

+0

Возможный дубликат: http://stackoverflow.com/questions/2564298/java-how-to-initialize-string – Gray

ответ

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

создает массив нулевых ссылок. Вы должны фактически инициализировать каждый один:

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

 Смежные вопросы

  • Нет связанных вопросов^_^