public class ThreadFlag extends Object
Class used to control running threads. A flag keeps a marker whether threads should or not continue and keeps record of which threads have reached the flag. It is essentially an implementation of a barrier.
Using this class several threads may keep a synchronization point. Lets suppose we have a process that divides into three phases, A, B and C and we want several threads in parallel to execute phase A. We want all threads to move to phase B when all have finished A. When all finish phase B we want all to start phase C. In order to do this we create two flags, one representing the end of phase A and the other the end of phase B. Each thread is now:
public void process(ThreadFlag flagA, ThreadFla flagB) {
doSomethingInPhazeA();
flagA.reach();
doSomethingInPhazeB();
flagB.reach();
doSomethingInPhazeC();
}
The method reach will block the current thread until someone
invokes the allowContinue method. So, if there were 20 threads
running, we could use a subclass of ThreadFlag to start all
threads into the next phase:
public class MyStartAllAtOnceFlag extends ThreadFlag {
public int count = 0;
public void threadReached(List l) {
if (l.size() == 20) {
// All threads have arrived.
allowContinue();
}
}
}
| Constructor and Description |
|---|
ThreadFlag()
Creates a new flag.
|
| Modifier and Type | Method and Description |
|---|---|
void |
allowContinue()
Starts all threads currently stopped at the flag.
|
void |
reach()
Invoked by a thread to mark that it has reached the flag.
|
List<Thread> |
reached()
Obtains the list of all threads that have reached the flag.
|
void |
threadReached(List<Thread> l)
A thread has reached the flag.
|
public void reach()
allowContinue() method has been
called) this method returns immediately.public void allowContinue()
public void threadReached(List<Thread> l)
l - the list of threads that have reached the flagCopyright © 2015. All rights reserved.