Search code examples
javamultithreadingthread-sleep

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

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