Ravekitty
Ravekitty

Reputation: 77

Thread.sleep() alternatives

I want this boolean to change from false to true after 5 seconds(This is the code I have currently)

checkUser = false;
    loginMessage2 = "Error connecting to server.";
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    checkUser = true;

But I don't want the entire client to freeze, I am not using multi threading or anything of the sort

Upvotes: 1

Views: 5664

Answers (1)

An SO User
An SO User

Reputation: 24998

You may want to consider looking into a Timer that executes 5 seconds after you ask it to execute. Execute the timer only once.

That way, you get what you want and at the same time you do not freeze the application. The timer itself is a different thread so it will not block your application.

Swing timer tutorial: http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html

A very very short example:

ActionListener listener = new ActionListener(){
  public void actionPerformed(ActionEvent event){
    checkUser = true;
  }
};
Timer checkUserTimer = new Timer(5000, listener); // the 5 second gap
checkUserTimer.start(); // start the timer.

Upvotes: 5

Related Questions