Let's say I have 2 threads, t1 and t2, and a lock object, m. Thread t1 is in an infinite loop, where at each iteration, it grabs a lock on m, does some work, unlocks m and starts over immediately. During one iteration, t2 requests a lock on m but gets blocked by t1 and has to wait. Now, when t1 unlocks m, is it guaranteed that t2 will obtain the next lock on m? or can t1 sneak ahead of it at the next iteration?
Generally, is there a queue set up for waiting threads? If t1 has the lock, and all remaining threads also wanting that lock get blocked in the following order: t2, t3, ..., will the remaining threads continue execution in the order that they were blocked (e.g. t2 runs, then t3, etc.)?
(I briefly perused the java spec and couldn't find the answer. If it's in there, please let me know, and I will go back to read more carefully.)
Thanks! (First SO post, woohoo!)
string = "No" then, print from run method prints last. Threads run independently of each other. There is no defined order and it may very well happen what you expected.
You cannot tell the thread scheduler which order to execute threads in. If you need to ensure that a certain piece of code which is running on thread A must run before another piece of code running on thread B, you must enforce that order using locks or wait() / notify() .
All Java threads have a priority, and the JVM serves the one with the highest priority first. When we create a Thread, it inherits its default priority. When multiple threads are ready to execute, the JVM selects and executes the Runnable thread that has the highest priority.
Yes, there is a queue and it can be fair or not. Fair queues are more expensive and non-fair are faster (who wins the CAS wins the lock). check java.util.concurrent.locks.AbstractQueuedSynchronizer for further info.
will the remaining threads continue execution in the order that they were blocked (e.g. t2 runs, then t3, etc.)?
The main issue is that they are executed concurrently/simultaneously, you can't truly define order for 2 events that are executed in the same time. But w/ fair (unrecommended due to extra costs) locks any thread that manages to enlist itself for the lock will get eventually get to own it.
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