Search code examples
javaloopsdo-whilethread-sleep

Thread.sleep(); in Java


Whenever I use Thread.sleep(); in a do while loop, the hints tell me, "Invoking Thread.sleep in loop can cause performance problems." I have heard this from many other websites and books. What is something I can use instead?

Here's the code:

import javax.swing.*;

public class Delay {

    public static void main(String[] args) throws Exception {
        int difficulty;
        difficulty = Integer.parseInt(JOptionPane
                .showInputDialog("How good are you?\n" + "1 = evil genius...\n"
                        + "10 = evil, but not a genius"));
        boolean cont;
        do {
            cont = false;
            System.out.println("12");
            Thread.sleep(500);

            String again = JOptionPane.showInputDialog("Play Again?");
            if (again.equals("yes"))
                cont = true;
        } while (cont);
    }
}

Solution

  • Try java.util.Timer and/or javax.swing.Timer. Play with them a bit, set initial delay, repetition period, etc. See what suits your needs.

    Be sure to check differences between these two timers, for starters take a look at this question: Why are there two Timer classes in Java(one under javax.swing, one under java.util )?

    Then try ScheduledExecutorService, as already suggested by @BoristheSpider.