Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread priority and Thread accuracy

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.

like image 696
TeaCupApp Avatar asked Sep 14 '11 08:09

TeaCupApp


People also ask

What is thread and thread priority?

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.

Can 2 threads have the same priority?

Threads have some priority. Because of that thread scheduler assign processor to thread. It is possible to have same priority to threads.

What do you mean by thread priority?

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.

Why do we need thread 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.


1 Answers

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.

like image 107
Peter Lawrey Avatar answered Sep 28 '22 20:09

Peter Lawrey