Will Thread priority increases accuracy of Thread.sleep(50);
?
As we know Threads aren't accurate when you call sleep for 50ms, But does it increases accuracy by any mean? If thread is listed as MAX_PRIORITY
.
Will be thankful for any kind of explanation.
In Java, a thread's priority is an integer in the range 1 to 10. The larger the integer, the higher the priority. The thread scheduler uses this integer from each thread to determine which one should be allowed to execute. The Thread class defines three types of priorities: Minimum priority.
Threads have some priority. Because of that thread scheduler assign processor to thread. It is possible to have same priority to threads.
Thread priorities are integers ranging between MIN_PRIORITY and MAX_PRIORITY (constants defined in the Thread class). The higher the integer, the higher the priority.
Thread priority in Java is a number assigned to a thread that is used by Thread scheduler to decide which thread should be allowed to execute. In Java, each thread is assigned a different priority that will decide the order (preference) in which it is scheduled for running.
The accuracy of sleep is down to the operating system. If you want greater accuracy you can use another OS. Another approach is don't sleep, you can busy wait instead. Or you can sleep for say 45 ms and busy wait for 5 ms.
If you have a task which you need to run 20 times per second, you are better off keeping track of when the tasks should run next and run it at the time (rather than wait a fixed amount of time) as what you do between sleeps will also take some time.
BTW This is what ScheduledExecutorService.scheduleAtFixedRate does for you.
It can sleep between task with micro-second accuracy (assuming the OS supports it) but it tries not to drift.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With