Home > database >  java: I am supposed to call a method 50x per second in the run method of a thread, ONLY WITH THE MET
java: I am supposed to call a method 50x per second in the run method of a thread, ONLY WITH THE MET

Time:05-01

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

CodePudding user response:

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.

  • Related