0

我遇到了多线程问题。当我尝试使用 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 循环等到两个线程都完成?

4

1 回答 1

4

您可能会考虑将代码切换为使用CountDownLatch. 您将创建如下所示的锁存器,并且所有 3 个线程将共享它:

final CountDownLatch latch = new CountDownLatch(2);

然后你的两个线程将在完成时递减计数器:

countDown.countDown();

你的等待线程会做:

countDown.await();

在两个线程都完成并且闩锁变为 0 后,它将被唤醒。

于 2013-04-03T14:43:35.597 回答