我目前尝试编写一个将客户发送到最短队列的应用程序。每个队列都有其自己的线程。在Queue类中,我有一个实例变量nrClients
,用于跟踪队列中有多少个客户端。
[在run方法中,我有一个while条件,仅当nrClients
大于0时才使线程保持运行,但是有时即使nrClients
为0也会进入while循环,从而在内部代码中触发了NullPointerException
那一会儿。我也有一个从0
到nrClients-1
的for循环,但有时它会进入该循环并给我一个Index 0 out of bounds for length 0
异常。这是我在该类中编写的代码:
public class Queue implements Runnable{
BlockingQueue<Client> queue;
private int nrClients;
private AtomicInteger waitTime;
private boolean isClosed=true;
public Queue(){
nrClients= 0;
waitTime = new AtomicInteger(0);
queue = new LinkedBlockingQueue<Client>();
}
public void addClient(Client c){
nrClients++;
queue.add(c);
waitTime.addAndGet(c.getServiceTime());
c.setWaitTime(waitTime.get());
}
private void removeClient(Client c){
nrClients--;
queue.remove();
}
@Override
public void run() {
while (nrClients>0) {
isClosed = false;
Client c = queue.peek();
try {
int mustWait = c.getServiceTime();
for (int i = 0; i < mustWait; i++) {
Thread.sleep(10);
c.decServiceTime();
waitTime.decrementAndGet();
}
} catch (InterruptedException e) {
}
removeClient(c);
}
if (nrClients == 0)
isClosed = true;
}
public AtomicInteger getWaitTime() {
return waitTime;
}
public String toString(){
if(nrClients==0){
return "closed";
}
else
{
String r="";
for(int i=0; i<nrClients; i++){
Client c = (Client) queue.toArray()[i];
r+="("+c.getID()+","+c.getArrivalTime()+","+c.getServiceTime()+"); ";
}
return r;
}
}
public boolean isClosed() {
return isClosed;
}
我似乎找不到导致这些异常的问题,如果您能指出问题所在,我将不胜感激。预先谢谢!
好像您正在其他线程中执行run
。由于nrClients
不是volatile
,因此不需要读取任何新值。话虽如此,我不喜欢其余代码的外观。