Pepe
Pepe

Reputation: 27

Problems with threads, making a game in Java

I'm doing a Snake game in Java. I have the basic functionability, but I want pause the game when I click on a button. But the problem I have is when I clic on this button, the game is paused, but when I click again the game doesn't recognize the controls. I have a method called Init, on this I initialize the thread "Hilo". I tried to make a second thread in which I put an actionPerformed for the button, but the problem continued, now I am more confused. Here is my code:

Thread hilo; //I declared the thread
String state=""; //It is for control de state (paused or no)

Runnable hiloFor = new Runnable() 
{
    public void run() 
    {
        Thread actual = Thread.currentThread();
        synchronized(actual) 
        {
            do
            {
                //Game instructions (there are a lot of them)
                if(state.equals("paused")) 
                {
                    actual.wait();
                }

            }while(!option.equals("Exit"));
        }
    }
};


//This is my action performed where I control if it is paused
public void actionPerformed(ActionEvent e)
{
    if ( e.getSource() == btnPause )
    { 

        if(state.equals("paused")) 
        {
            cont(); //method for reactive the thread
            state="";
        }else if(state.equals(""))
        {
            state="paused";
        }
    }

}

If somebody can help me, I will be very glad, It has turned difficult to me.

Upvotes: 0

Views: 112

Answers (2)

Tomas Smagurauskas
Tomas Smagurauskas

Reputation: 706

if(state.equals("paused")) 
{
    actual.wait();
}

This part actually pauses the thread, until it's told to start it's work again. I suppose what you wanted in this case is something like continue; in loop, which, although, is not a very elegant way to do this. More suitable way to do this would be using notify().

Upvotes: 0

Thomas Stets
Thomas Stets

Reputation: 3045

To reactivate the Thread in wait() you must call notify() (or better notifyAll()) on the same object.

Your code looks like you expect to pause the Thread you call wait() on. This is not the case. wait() will always pause the thread making the call, not the object that is the target. You can use any object for the wait() / notifyAll() signaling, it just has to be the same object for both sides of the communication.

This pages has some good explanations: http://javamex.com/tutorials/synchronization_wait_notify.shtml

Upvotes: 1

Related Questions