How to avoid a thread stealing the turn of another thread?

N

Nafai

Let's have an example (just a generic program with threads and a monitor)


class MyMonitor {
....
public synchronized void m()
{
...
while(...) wait(); // (A)
...
notifyAll();
}

};

class MyThread implements Runnable {
....
MyMonitor m;
MyThread(MyMonitor m) { this.m=m;}
public void run()
{
while(true){
...
sleep(...);
// A thread can get monitor here even if there
// are threads waiting (but already notified) in (A)
m();

...
}
}

}

class MainProgram {
public static void main(String[] argv)
{
MyMonitor m = new MyMonitor();
MyThread t1 = new MyThread(m);
MyThread t2 = new MyThread(m);
t1.start();
t2.start();

}


How can I avoid that a thread (which is about to get into the monitor)
steals the turn of the monitor of a thread which has been waiting but
has been notified?

Thanks.
 
M

Mark Thornton

Nafai said:
How can I avoid that a thread (which is about to get into the monitor)
steals the turn of the monitor of a thread which has been waiting but
has been notified?

Have a look at the classes in java.util.concurrent. Some of these accept
a fairness parameter which will then ensure first in first out ordering
of threads.

Mark Thornton
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,740
Latest member
AdolphBig6

Latest Threads

Top