"Relinquish the thread's timeslice" and "sleep" both mean approximately the same thing. If you want a delay that does not "sleep," then you need your thread to "spin," doing nothing, for that amount of time. E.g.,
static void spin(long delay_in_milliseconds) {
long delay_in_nanoseconds = delay_in_milliseconds*1000000;
long start_time = System.nanoTime();
while (true) {
long now = System.nanoTime();
long time_spent_sleeping_thus_far = now - start_time;
if (time_spent_sleeping_thus_far >= delay_in_nanoseconds) {
break;
}
}
}
A call to spin(n)
will burn CPU time for n
milliseconds, which is the only way to delay a thread without "relinquishing the time slice."
P.S., You said, "I saw that it [sleep()
] won't work..." Why is that? What did you see? Did you actually measure the performance of your program, and find that it is not satisfactory? or is your program failing to meet some hard real-time requirement? If your program has real-time requirements, then you might want to read about the "Real-time Specification for Java" (RTSJ).
See Also, https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/System.html#nanoTime()