对于家庭作业,我正在为管理多个执行事务的线程的服务器编写一个stop()方法。 Stop()应该是1.向命令队列提交一个停止命令,并且2.在所有线程上调用join(),以便交易有机会完成。
但是,join()未按预期工作。当我尝试调用join()时,我得到一个NullPointerException。我修改了服务器线程以便在我提交停止命令后等待一秒钟,但是当我应该使用join()时,这是一个糟糕的替代品。
public void stop() throws InterruptedException {
// TODO Auto-generated method stub
System.out.println("server stop()");
for (CommandExecutionThread thread : threads) {
System.out.println(threads.length);
}
for (CommandExecutionThread thread : threads) {
Command e = new CommandStop();
queue.add(e);
}
for (CommandExecutionThread thread : threads) {
if (thread != null)
{
thread.join();
}
if (thread == null)
{
System.out.println("NULL thread"); //threads are always null at this point
}
}
for (CommandExecutionThread thread : threads) {
System.out.println(threads.length);
}
wait(1000);//simulate the wait that I would have had from join()
}
来自commandQueue的CommandExecutionThreads poll()命令,当遇到stop命令时,它返回:
public void run() {
while (true) {
synchronized (commandQueue) {
while (commandQueue.isEmpty()) {
try {
commandQueue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}//end while(commandQueue.isEmpty())
}//end synchronized(commandQueue)
Command c;
synchronized (commandQueue) {
c = commandQueue.poll();
if (c.isStop()==true)
{
System.out.println("\tSTOP");
return;
}
else
{
//System.out.println("\tTRANSACTION");
}
if (executeCommandInsideMonitor) {
try {
c.execute(bank);
} catch (InsufficientFundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
commandQueue.notifyAll();
} // end sync commandQueue
} //end while(true)
}//end run()
我在创建银行服务器时更早地初始化了我的线程数组。线程本身在可用时将命令从队列中拉出。出于诊断目的,我已经打印出thread.isAlive()并且可以正常工作。当我在stop方法中时,thread.isAlive()抛出一个空指针错误:
public class BankServerImpl implements BankServer {
Queue<Command> queue = new LinkedList<Command>();
CommandExecutionThread[] threads;
boolean executeCommandInsideMonitor;
Bank bank;
/**
* Constructor for BankServerImpl, which implements BankServer
*
* @param bank
* @param serverThreads
* @param executeCommandInsideMonitor
*/
public BankServerImpl(Bank bank, int serverThreads, boolean executeCommandInsideMonitor) {
this.bank = bank;
this.executeCommandInsideMonitor = executeCommandInsideMonitor;
threads = new CommandExecutionThread[serverThreads];
for(CommandExecutionThread thread : threads) {
thread = new CommandExecutionThread(bank, queue, executeCommandInsideMonitor);
thread.start();
System.out.println(thread.isAlive());
}
}
答案 0 :(得分:2)
创建线程时,永远不要将它们插入到数组中。
for(CommandExecutionThread thread : threads) {
thread = new CommandExecutionThread(bank, queue, executeCommandInsideMonitor);
thread.start();
System.out.println(thread.isAlive());
}
此代码不会导致更新阵列。你需要这样的东西:
for (int i = 0; i < serverThreads; i += 1) {
CommandExecutionThread newThread = new CommandExecutionThread(bank, queue, executeCommandInsideMonitor);
threads[i] = newThread;
newThread.start();
System.out.println(newThread.isAlive());
}