Reputation: 39
I am implementing multi-thread and want to be able to send/receive message to/from each thread from the main. So I am trying to setup a blocking queue for each thread with the following code:
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) {
}
}
}
}
the code compiled but during run time it give me a NullPointerException on the line queue[j].put("quit");
it worked with just 1 queue BlockingQueue queue = new LinkedBlockingQueue(5);
I believe its because the array isnt properly initialized, I tried declare it as BlockingQueue[] queue = new LinkedBlockingQueue10;
but it gives me "; is expected"
anyone know how to fix this? I am using netbeans IDE 7.3.1.
thanks.
Upvotes: 0
Views: 2663
Reputation: 41281
BlockingQueue<String>[] queue = new LinkedBlockingQueue[5];
creates an array of null references. You need to actually initialize each one:
for(int i=0; i<queue.length; i++){
queue[i]=new LinkedBlockingQueue(); //change constructor as needed
}
Upvotes: 4