Thread.sleep(); in Java
每当我使用Thread.sleep();在do while循环中,提示告诉我:"在循环中调用Thread.sleep可能会导致性能问题。"我已经从许多其他网站和书籍中听到了这一点。我可以用什么代替?
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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?\ " +"1 = evil genius...\ " +"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); } } |
尝试使用java.util.Timer和/或javax.swing.Timer。与他们一起玩,设置初始延迟,重复周期等。查看适合您需要的内容。
请务必检查这两个计时器之间的区别,对于初学者而言,请看以下问题:为什么Java中有两个Timer类(一个在javax.swing下,一个在java.util下)?
然后尝试@BoristheSpider已经建议的ScheduledExecutorService。
使用