Would there be any Thread.sleep problems?

I’ve been lurking around various websites and reading up on many different threads over the past few days and I noticed that a few people were saying not to use Thread.sleep for various reasons that I can’t currently remember.

I was wondering if it’s alright to be using Thread.sleep() in this circumstance:

class MessageDisplay
{
	public MessageDisplay()
	{
	}
	
	//NOTE: You may need to add a way to decide where to print the message or else this wont work!
	public void typeWriterDisplay(String x, int y) //Requires a string to display and an int to decide how long to wait between displaying letters.
	{
		for (int i = 0; i < x.length(); i++)
		{
			System.out.print( x.charAt(i) );
			try
			{
				Thread.sleep(y);
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}
		}
	}
}

I’m using it to display strings character-by-character with a small delay between characters.

The only reason people have been saying not to use Thread.sleep(), because it is unreliable when it comes to tracking fixed time steps. Each OS has a different way of interpreting Thread.sleep() which will end up in a game running a lot slower on one PC than the other.

However, just because it is unreliable doesn’t mean that you shouldn’t use it. I think the only real weakness is that you make your game slightly less professional. Actually, even with variable time step, it still will fall weakness to lag spikes and your game will end up sputtering instead. (Though these things are barely noticeable with LWJGL because the frame rate is so much better anyway.)

Ah, that makes sense, thanks!
Do you know of any other ways to get this sort of character-by-character effect using the regular java libraries and without thread.sleep(), I’d rather avoid the laggy look that you were describing.

Many ways, something like this f.ex:

String renderString = null;
String text = "hello";

long lastTime = System.currentTimeMillis();
long delay = 100; // 100 ms

run() {
  while (true) {
    tick();
    render();
    // probably limit the FPS somehow here
  }
}

tick() {
  long now = System.currentTimeMillis();
  // update string
  if ( now - lastTime > delay ) {
    renderString += text.charAt( renderString.length() + 1 );
    lastTime = now;
  }
}

render() {
  Graphics g = getGraphics();
  g.drawString( 0, 0, renderString );
}