问题
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