我遇到了多线程问题。当我尝试使用 wait() 和 notify() 或 join() 时,我得到了 InterruptedException。我在 WHILE 循环中有 2 个线程,我想等到它们都完成。这是我的代码:
while (!GamePanel.turn)
{
if(GamePanel.s.isRunning)
{
synchronized (GamePanel.s.thread)
{
try {
GamePanel.s.thread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//Player selected random moves
if(GamePanel.selectedMove == 1)
{
//Get computer's Random move.
strategy.getRandomMove();
}
else
{
//Player selected AI moves
if(GamePanel.selectedMove == 2)
{
//Get computer's AI move.
strategy.getMove();
System.out.println(strategy.move);
}
}
//Perform the next move of the computer.
Rules.makeMove(GamePanel.dimples, strategy.move, false);
}
strategy.getMove() 和 Rules.makeMove() 都是线程。对于每个线程,我创建了自己的 start() 和 stop() 方法:
public void start()
//This function starts the thread.
{
if (!isRunning)
{
isRunning = true;
thread = new Thread(this);
thread.setPriority(Thread.NORM_PRIORITY);
thread.start();
}
}
private void stop()
//This function stops the thread.
{
isRunning = false;
if (thread != null)
{
thread.interrupt();
}
thread = null;
}
我也尝试过 thread.stop() 但仍然存在同样的问题。 我的问题是如何让 WHILE 循环等到两个线程都完成?