Java Multithreading priority: Why in this example, sometimes t1 occurs before t2 is completed, even if t2 has higher priority? Java Multithreading priority: Why in this example, sometimes t1 occurs before t2 is completed, even if t2 has higher priority? multithreading multithreading

Java Multithreading priority: Why in this example, sometimes t1 occurs before t2 is completed, even if t2 has higher priority?


Your lower-prioritized thread is started first, therefore it may in some cases complete even before the higher-prioritized even starts. 5 iterations is not that much.On my (Windows) machine, if I replace the number of iterations with 100, the higher-prioritized thread is consistently selected first.


As you already mentioned in your post:

“Threads with higher priority are executed in preference to threads with lower priority.”

This does mean, that a thread with higher priority has a higher likeliness of being executed than a low-priority-thread. It doesn't mean that a thread with higher priority will always be executed first/finish first. The actual thread-handling depends upon the OS (java simply uses the thread-libraries provided by the OS it runs on).


My notes about threads priorities:

  • You can use it for improving performance
  • Priorities depends on OS (Windows has 7, Linux ignores them)
  • Don't design your app in way where correct working depends on priorities
  • If there are some threads with high priorities which are never deactivated, threads with lower priorities can never be run