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);
我相信它,因爲數組心不是正確的初始化,我想聲明爲BlockingQueue[] queue = new LinkedBlockingQueue10;
,但它給了我「;預計」
人知道如何解決這一問題?我正在使用netbeans IDE 7.3.1。
謝謝。
可能的重複:http://stackoverflow.com/questions/2564298/java-how-to-initialize-string – Gray