Creating a pause or waiting effect in java program

只谈情不闲聊 提交于 2019-12-02 10:33:21

问题


I am writing a simple fishing simulator game in Java. I wanted there to be a randomly generated waiting time after each cast. When the wait was over, a random event would occur(a fish would be caught, a fish would steel your bait, etc). I have heard allot of bad things about Thread.sleep() and was wondering what would work best for me in this situation.

currently I am using something like this

Random random = new Random();
long time = System.currentTimeMillis();
long difference = random.nextInt(9000);
boolean timeMet = false;

while(!timeMet){
   if((time + difference) <= System.currentTimeMillis())
      timeMet = true;
}

return event;

回答1:


You could consider using a SwingTimer.

Check out this similar post.

On the topic of whether Thread.sleep is bad or not, check out this post.




回答2:


What have you heard bad about Thread.sleep(millis)? Using the cpu to keep busy for some period of time is quite wasteful.

Just use Thread.sleep(difference);



来源:https://stackoverflow.com/questions/22002414/creating-a-pause-or-waiting-effect-in-java-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!