-3

I have to call a method in the run method of a thread 50 times in one second, the problem is, i am only allowed to use sleep as a method!

Now the problem is how can i do that, other threads here for instance:

java- Calling a function at every interval

do that with a timer.

With a timer its easy. But i am only allowed to use sleep as a method...

mdioeh
  • 1
  • 1
  • 50 times per second is once every 20 milliseconds. Track the number of elapsed milliseconds in the runtime of your method/operation (`System#currentTimeMillis`), then sleep for `20 - interval` milliseconds – Rogue Apr 30 '22 at 18:38
  • Puuh. How could I make that? For example I am making: long temporary = currentTimeMillis(); Now I have that and then? need I to do sleep(currentTimeMillis()/20)? – mdioeh Apr 30 '22 at 18:42
  • If you defined `temporary` right before your operation, then `System.currentTimeMillis() - temporary` _after_ your operation would be the elapsed milliseconds. – Rogue Apr 30 '22 at 19:13

2 Answers2

0
while (true) {
    long t0 = System.currentTimeMillis();
    doSomething();
    long t1 = System.currentTimeMillis();   
    Thread.sleep(20 - (t1-t0));
}

t1 minus t0 is the time you spent in 'doSomething', so you need to sleep for that much less than 20 mS.

You probably ought to add some checks for t1-t0 > 20.

dangling else
  • 438
  • 2
  • 3
0

You cannot avoid jitter in timing based on System.currentTimeMillis() (or, based on any other system clock).

This solution will not accumulate error due to jitter (unlike another answer here that measures how long the task actually took on each iteration of the loop.) Use this version if it's important for the task to be performed exactly the right number of times over a long span of time.

long dueDate = System.currentTimeMillis();
while (true) {
    performThePeriodicTask();

    dueDate = dueDate + TASK_PERIOD;
    long sleepInterval = dueDate - System.currentTimeMillis();
    if (sleepInteval > 0) {
        Thread.sleep(sleepInterval);
    }
}
Solomon Slow
  • 25,130
  • 5
  • 37
  • 57