1

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);
    }
}
alterfox
  • 1,675
  • 3
  • 22
  • 37
  • Look at [`Timer`](http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html) or [`ScheduledExecutorService`](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html). Timer is a little obsolete but it's easier to get a grip on. ScheduledExecutorService is current best practice. – Boris the Spider Oct 06 '13 at 21:52
  • When you paste code, highlight it all and press "Ctrl + K" to avoid it doing what it has here, not highlighting all of it. – IHazABone Oct 06 '13 at 21:53
  • Why do you think you need to sleep at all? – user207421 Oct 06 '13 at 22:03
  • @EJP good point - hadn't really thought about _why_ the OP was sleeping the `Thread`. – Boris the Spider Oct 06 '13 at 22:38

2 Answers2

1

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.

Community
  • 1
  • 1
alterfox
  • 1,675
  • 3
  • 22
  • 37
-1

Using Thread.sleep to do polling or similar update mechanism is ok approach. It's reasonable for instance if you want to repaint a canvas every 5 milliseconds, then you would use sleep(5). You could also use a hardware timer which will be more exact and relieve the CPU, but the usual approach is exactly Thread.sleep.

Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424
  • No it isn't. In this situation the usual approach, or at least the *correct* approach, is to use a javax.swing.Timer. – user207421 Oct 06 '13 at 22:06
  • 1
    This is a piece of terrible advice. It might be _your_ usual approach but it certainly isn't accepted practice and if one of my developers used it there would be trouble. – Boris the Spider Oct 06 '13 at 22:37