简体   繁体   中英

Java - Application crashed on Thread.sleep method

I have a function for my monsters to walk. It will be able to choose the direction and distance randomly and move the monster when called. Right now I have the method being called every frame in the render method:

for(Monster monster : monsters) {
            renderer.processEntity(monster);
            monster.monsterWalk();
}

This is good so far, but it makes the monster shake around because it is rapidly choosing values, I want it to move somewhere, wait 5 seconds, and then make another decision on where to move.

My problem is when I add the Thread.sleep(x) method, and the screen goes black and the program becomes unresponsive.

Here is the walk method:

public void monsterWalk() {

    //Make direction decision
    Random random = new Random();

    switch(random.nextInt(4)) {
    case 0:
        setPosition(new Vector3f(position.x, position.y, position.z += mobSpeed)); //forward
        break;
    case 1:
        setPosition(new Vector3f(position.x, position.y, position.z -= mobSpeed)); //backward
        break;
    case 2:
        setPosition(new Vector3f(position.x += mobSpeed, position.y, position.z)); //right
        break;
    case 3:
        setPosition(new Vector3f(position.x -= mobSpeed, position.y, position.z)); //left
    }

    try {
        Thread.sleep(random.nextInt(5000) + 1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }   
}

I haven't used LWJGL myself, but in almost every UI framework I've seen, there's one thread which is reserved for UI operations:

  • You mustn't perform UI operations on any other thread
  • You mustn't tie that thread up for any significant time, as the UI can't refresh while it's blocked

In your code, you're calling Thread.sleep which blocks the thread for that period of time - if you do that on a UI thread (and if LWJGL works in the same way as those other frameworks) then you're preventing the UI from refreshing while it's blocking.

To perform actions periodically, you should use a timer of some sort. The tricky part is that you'd want the timer to fire in the UI thread . Most frameworks provide some sort of dedicated support for this (eg Swing Timer ) but I don't know if LWJGL does. Hopefully that's enough information to get you started looking for the best approach within LWJGL.

I note the LWJGL timing documentation talks about this sort of thing a bit, but it's not quite the same. (It also refers to Display.sync , which I then can't find in the Javadoc, so it may be referring to an older version.)

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