Batonpublic class Baton extends Object A concurrency control mechanism, a virtual baton that can be passed between
two threads to control the order of execution. The main operation is
pass(), which unblocks the other thread and then blocks this thread until
the other thread passes the baton back.
A typical use case is as follows:
1. Thread A creates the baton and passes it to thread B.
2. Thread A calls start() to wait for thread B to get to a known state.
3. Thread B calls pass() to pass the baton to A, and then B blocks.
4. Thread A unblocks does stuff, then calls pass() to pass the baton
to B, and then A blocks.
4. Threads A and B alternately call pass() so that they execute in
lock step.
5. One of the threads calls finish() to let the other thread continue
indefinitely, ending the use of the baton.
The baton can be passed between threads up to Integer.MAX_VALUE - 1 times
before it ceases to function. |
Constructors Summary |
---|
public Baton()Creates a new baton.
count = 0;
|
Methods Summary |
---|
private void | await(int seq)
while (count < seq) {
try {
wait();
} catch (InterruptedException ignore) { }
}
| public synchronized void | finish()Tells the other thread continue, and then returns. After a call to
finish(), the baton becomes inoperative, and calls to pass() simply
return.
count = Integer.MAX_VALUE;
notifyAll();
| public synchronized void | pass()Passes the baton to the other thread, unblocking it, and blocks until
the baton is passed back. After finish() is called, simply returns
without doing anything.
if (count < Integer.MAX_VALUE) {
count++;
notifyAll();
await(count + 1);
}
| public synchronized void | start()Starts the protocol by waiting for the first pass from the other
thread.
if (count > 1) {
throw new IllegalStateException();
}
await(1);
|
|