1

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;
Michael Riess
  • 75
  • 1
  • 8

2 Answers2

2

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.

Community
  • 1
  • 1
ElliotSchmelliot
  • 7,322
  • 4
  • 41
  • 64
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);

ErstwhileIII
  • 4,829
  • 2
  • 23
  • 37
  • http://msmvps.com/blogs/peterritchie/archive/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program.aspx It's just one resource, but I was still worried. I wanted to get opinions from allot of people before deciding what to do – Michael Riess Feb 25 '14 at 01:02
  • All of those examples have to do with Threading. It doesn't look like you are using Threads, so ignore it. – Nathan Merrill Feb 25 '14 at 01:04
  • Ya, I'm fairly new to Java and honestly have no clue what threading is. – Michael Riess Feb 25 '14 at 01:06
  • Until you start using mulitple code streams that may run concurrently, you can just think of your code running in a single cpu core (a "thread"). In this case, Thread.sleep(millis), just specifies that you want your program to give up the cpu for a period of time and then have the OS return control to your program. – ErstwhileIII Feb 25 '14 at 01:08
  • What about the Swing Timer? – Michael Riess Feb 25 '14 at 01:11