0

I am working on a Java program that runs forever, but I don't know how to delay each loop for one second without using 'try catch'. I've tried

import java.util.concurrent.TimeUnit;

public class program {
    public static void main(String[] args) {
        TimeUnit wait = new TimeUnit();
        while (true) {
            wait.SECONDS.sleep(1);
        }
    }
}

but it didn't seem to work. Can anyone help me?

Alpha
  • 36
  • 1
  • 5
  • 2
    There is no need to create an instance of TimeUnit. SECONDS is a static field, so you can refer to it directly as TimeUnit.SECONDS. Also, if you don't want to use try-catch, you can do `public static void main(String[] args) throws InterruptedException`, – k314159 Mar 12 '21 at 18:19
  • Hello! Why are you trying to delay every loop by a second? Do you have tasks that need to run once every second? Or are you waiting for something to finish? What is your goal? – Petr Janeček Mar 12 '21 at 18:30
  • Why don't you want a try/catch? – NomadMaker Mar 12 '21 at 18:55
  • @k314159 thank you this helped me the most – Alpha Mar 12 '21 at 19:25

4 Answers4

5

After contemplating this for a while I do agree that Thread.sleep is the straight forward way to stall the main thread in a loop obviously.

In other use cases that may be differnt, though, since, well, it stalls a thread that could do something else in the meantime. Here you have a discussion of Timer vs Thread.sleep, if you're interested and here another somewhat less comprehensive answers for a question that could pass as a duplicate.

public static void sleep(int someDelay) {
   try {
      Thread.sleep(someDelay);
   } 
   catch (InterruptedException e) {
      Thread.currentThread().interrupt();
   }
}

For more demanding scenarios ScheduledThreadPoolExecutor is your friend.

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(poolSize);
    executor.schedule(() -> {
        // doSmthg
    }, 12, TimeUnit.HOURS);

Another way to go was Timer/Timertask, which is now usually discouraged (thx to @rkosegi for pointing this out) in favor of ScheduledThreadPoolExecutor. A poolsize of 1 mimicks Timer/Timertask functionality.

On the other hand Timer/Timertask has the upper hand for large numbers of small tasks in a single thread scenario "Implementation note: This class scales to large numbers of concurrently scheduled tasks (thousands should present no problem). Internally, it uses a binary heap to represent its task queue, so the cost to schedule a task is O(log n), where n is the number of concurrently scheduled tasks.", where ScheduledExecutorService uses a BlockingQueue.

new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            // do smthg;
        }
    }, someDelay);
Curiosa Globunznik
  • 3,129
  • 1
  • 16
  • 24
  • In fact this answer could be very useful to the OP, as I suspect it's an [X-Y problem](https://en.wikipedia.org/wiki/XY_problem). A timer task could be better suited than a wait in a loop. – k314159 Mar 12 '21 at 18:26
1

The most straightforward way is to create a method.

public static void sleep(int delay) {
   try {
       TimeUnit.SECONDS.sleep(delay);
   } catch (InterruptedException ie) {
      Thread.currentThread().interrupt();
   }
}

Now just call the method when ever you need to sleep.

for (int i = 0; i < 10; i++ ) {
    System.out.println(i);
    sleep(1);  // 1 second
}
WJS
  • 36,363
  • 4
  • 24
  • 39
0

You can use Thread.sleep(TIME_FOR_DELAY) line for delay But you have to put it inside try-catch block

try{
   //TODO before wait

   Thread.sleep(TIME_FOR_DELAY);

   //TODO after wait
}catch(InterruptedException e){
   // 
}
Jimmy
  • 995
  • 9
  • 18
0

Someone said that I should do this

import java.util.concurrent.TimeUnit;

public class program {
    public static void main(String[] args) throws InterruptedException {
        while (true) {
            TimeUnit.SECONDS.sleep(1);
        }
    }
}

and it worked. Thank you that person

Alpha
  • 36
  • 1
  • 5