简体   繁体   中英

Java Thread sleeping but the code after doesn't work?

I have a thread im trying to run in Java, for a game Im making. The thread essentially sleeps for a bit, updates the objects, then calls repaint(). Seems like it should work great, it looks like the code Ive found on the internet, but it doesn't work.

The code is here:

@Override
public void run() {
    int sleep = 500;
    Dimension dim = getSize();
    while(true){
        try {
            Thread.sleep(sleep);
            System.out.println("Sleeping!");
        } catch (InterruptedException e) {
            System.out.println("interrupted");
        }
        for(int i = 0 ; i < poop.size() ; i++){
            poop.get(i).update(dim.width, dim.height);
            System.out.println("Y is: "+poop.get(i).getYCoord()+" Step is: "+poop.get(i).getYStep());
        }
        repaint();
        }
}

The problem occurs when I put the try catch block into the for loop, that calls fine, the System.out prints the Y coordinate as well, but the update doesn't work anymore. Any ideas would be awesome. IF you need more code, tell me, Ill put the update code on here too. Also treat me like a beginner to threads casue I more or less am, also a beginner more or less to the swing library im using.

Here's the update() code:

@Override public void update(int screenWidth, int screenHeight)
{
    xCoord += xStep;
    if (xCoord > screenWidth) {
        xCoord = 0;
    } else if (xCoord < 0) {
        xCoord = screenWidth;
    }

    yCoord += yStep;
    if (yCoord > screenHeight) {
        yCoord = 0;
    } else if (yCoord < 0) {
        yCoord = screenHeight;
    }
}

Even though this code is in a run() method and presumably in a Runnable object, your description is symptomatic of calling Thread.sleep(...) on the Swing event thread. If you do that, you put the whole GUI to sleep since the event thread that you're sleeping is responsible for drawing the GUI and interacting with the user.

Solution: don't do that. Do any long running task or sleeping in a background thread such as in a SwingWorker.

Alternatively, get rid of your Thread.sleep(...) 's and use a Swing Timer instead.

You're not calling repaint() until after the for loop is completely finished. So sticking the sleep inside there isn't going to cause it to repaint one thing at a time every 500 milliseconds. It's going to cause it to take size() * 500 just to get through the loop, then repaint everything all at once.

The problem here is that the Dimension dim = getSize(); is setting both to 0 for some reason. Therefore the update method couldn't do it's job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM