I have been learning about multi-threading in
Java for some months and have practiced them with examples. From what I know, when using wait/notify, if n threads are waiting on an object, one random
thread is notified when notify() is called. Recently, for an interview I was asked this question:
If there are 10 threads T1 to T10, and T2-T10 are dependent on a result from T1 and are waiting for that object. Now the first thread that enters wait for this object should be given higher priority than the next and so on. So eg: T4 calls wait() before T3, then when the notify is called T4 should be notified and should run before T3.
I think you can use a static volatile member which has some value say 10 and you can setPriority for every Thread just before going into wait() by using this static value and then reduce the value by 1. Then use notifyAll. Since it is guaranteed that the thread with the highest priority will always be selected to run before the thread with the lowest priority, this should work right?
Or is there another technique to solve this problem?
<Edit> Already see a problem with this since priority can be 1-10 or 1-5 depending on the OS, so this solution does not work and does not even scale to more threads. Another solution I thought of was to put the Threads in a queue in the order of them calling wait() but then how to select them.