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

Forum statistics

Threads
473,754
Messages
2,569,525
Members
44,997
Latest member
mileyka

Latest Threads

Top