'java: I am supposed to call a method 50x per second in the run method of a thread, ONLY WITH THE METHOD SLEEP (All other threads here with timer)

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...



Solution 1:[1]

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.

Solution 2:[2]

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);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dangling else
Solution 2 Solomon Slow