0

How I can determine which thread is waiting for more time?

My requirement is, in a synchronized methods, when one thread finishes its work, I want to allow the thread which is waiting for the longest time. I hope my question make sense.

rlandster
  • 7,294
  • 14
  • 58
  • 96
Vikram P
  • 85
  • 2
  • 11
  • 2
    Sorry, it doesn't. Also, I get the faint idea that you're talking about java? – EboMike Oct 15 '10 at 06:57
  • There is (also assuming Java) no way to get this information. The scheduler will decide which thread goes next, probably using the thread priority. – Thilo Oct 15 '10 at 06:59
  • @Thilo, I don't think that is completely true. Have you ever seen the solution to the Dining Philosophers problem? I once saw a solution to that problem that showed exactly how long a philosopher (thread) had been waiting to eat (execute). It was written in C, I'll try to scrounge up the code tomorrow. – ubiquibacon Oct 15 '10 at 07:06

3 Answers3

2

All depends on which language and/or environment you are using. So far as I know there's no intrinsic support for this in Java, if multiple threads are waiting to enter a synchronized method then the system will pick an arbitrary one to run when entry is possible.

If instead you use Java's wait() / notify() then you control which threads are notified and so can build your own priority mechanism, for example you could have a simple queue to which each thread adds itself before its wait() then you just take the top item from the queue and notify that thread.

djna
  • 54,992
  • 14
  • 74
  • 117
1

@djna Java doesn't let you choose which thread to notify. If 10 threads are in the queue any one of them can be notified.

This can be done by using the lock/condition interfaces in concurrent package. Here you can associate each of these threads with a condition and then take out an item from that queue and signal the condition that is mapped with that thread/task.

ЯegDwight
  • 24,821
  • 10
  • 45
  • 52
maximus
  • 19
  • 2
1

You should not and almost certainly do not need to do this.

The threading environment will schedule threads for you.

If the software design is such that this appears to be a problem, then the design is incorrect for a pre-emptive threading environment.

What you may want to be doing is something more like managing and prioritizing units of work, where you for example service work in the order that it arrives.

In other words, the order of work processing should not in your design depend on which thread runs, but rather, on your design of how work is handed out to threads.