Search code examples
javaobjectthread-sleep

Can I use an object to call Thread.sleep?


very new to java and Im trying to create a small text based choose your own adventure game. As the text you have to read for the game is appearing, im using Thread.sleep to give some time in between each line of text. My problem is the page gets filled quite easily this way with bulky chunks of using Thread.sleep. Is there any way I could maybe create an object that initiates the Thread.sleep command and I could simply call it so it would perform that waiting period.

I basically want to make the code below into an object and call it when I need that Thread.sleep action performed. So my code isnt so bulky and long.

try {
    Thread.sleep(3000);
}
catch (InterruptedException ex)
{

}

Solution

  • You wouldn't necessarily make that block of code into an object in a trivial use case like this. You could just make it into a method, then call that method anytime you want that code to execute instead of copy/pasting it. Example:

    public void doSleep(int ms){
      try {
         Thread.sleep(ms);
      }
      catch (InterruptedException ex) {
          … // Handle thread being interrupted. See: https://stackoverflow.com/q/1087475/642706
      }
    }
    

    you can then call this by doSleep(3000);. Pass any integer value you want into the method call to make it sleep for that many milliseconds.

    See more on methods here https://www.geeksforgeeks.org/methods-in-java/