简体   繁体   中英

JAVA waking up threads in specific order

Let's say that i have 10 active threads and only 3 resources (of something) while the first three threads got the resources i want all other thread that try to get the resource to wait but that the wake up or notify will be in fifo order i mean that the first thread that got the waiting will be the first to wake up. thank you all.

I think this link explains it quite well: https://www.safaribooksonline.com/library/view/java-threads-second/1565924185/ch04s03.html

When using notify it is impossible to decide or determine in advance which thread will be allowed to execute. I see 2 solutions to this:

  • Use notifyAll() and let each thread check for itself whether whose turn it is (eg by using a synchronised FIFO queue)
  • Use the method described in the link: let each thread wait on a different object and use 1 thread that has as it's sole purpose to notify the correct object. This seems like the best solution to me.

Java generally doesn't decide these things however if you use a fair lock eg

Lock lock = new ReentrantLock(true);

then those threads will acquire the lock in the order they were attempted. This works by disregarding the order thread would be notified and ensuring a lock which is not taken unless the thread is next on the FIFO queue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM