Ron537
Ron537

Reputation: 990

Multithreading issue can't wait for thread to finish

I am having problem with multithreading. When I am tring to use wait() and notify() or join() I am getting InterruptedException. I have 2 threads in a WHILE loop and I want to wait until both of them are finished. this is my code:

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);
    }

both strategy.getMove() and Rules.makeMove() are threads. for each thread I've created my own start() and stop() methods :

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;
}

I have also tried to do thread.stop() but still same problem. My question is how can I make the WHILE loop to wait until both threads are done??

Upvotes: 0

Views: 127

Answers (1)

Gray
Gray

Reputation: 116858

You might consider to switching your code to use a CountDownLatch. You would create the latch like the following and all 3 threads would share it:

final CountDownLatch latch = new CountDownLatch(2);

Then your two threads would decrement the counter as they finish:

countDown.countDown();

And your waiting thread would do:

countDown.await();

It would be awoken after both of the threads finish and the latch goes to 0.

Upvotes: 4

Related Questions