简体   繁体   中英

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);
    }
}

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.

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 .

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