public class Sync extends Object
This is just a CyclicBarrier, but with timeouts and exceptions built in that are more suitable
for writing tests.
This establishes that everything before the sync() in every associated thread
happens-before everything after it. Two of them in a row therefore
usually signifies one thread handing control over to another, then waiting to receive
control back again. This can be used instead of a series of barriers to repeatedly
exchange control between two or more threads. For example, these two threads would
print the numbers 1 through 5 in order:
// in thread 1
System.out.println(1);
sync.sync(); // Sync A: thread1 => thread2
sync.sync(); // Sync B: thread1 <= thread2
System.out.println(3);
sync.sync(); // Sync C: thread1 => thread2
sync.sync(); // Sync D: thread1 <= thread2
System.out.println(5);
// in thread 2
sync.sync(); // Sync A: thread1 => thread2
System.out.println(2);
sync.sync(); // Sync B: thread1 <= thread2
sync.sync(); // Sync C: thread1 => thread2
System.out.println(4);
sync.sync(); // Sync D: thread1 <= thread2
You can also create a Sync with more than two parties for coordinating
the flow of control among even more threads, but a series of barriers would
probably be easier to understand for that.
| Constructor and Description |
|---|
Sync()
Creates a thread synchronization point to coordinate
2 threads. |
Sync(int parties)
Creates a thread synchronization point to coordinate the given number of threads.
|
| Modifier and Type | Method and Description |
|---|---|
void |
sync()
Synchronizes the threads using
Barrier.getDefaultTimeout() as the timeout. |
void |
sync(long millis)
Synchronizes the threads using the specified timeout in milliseconds.
|
void |
sync(long timeout,
TimeUnit units)
Synchronizes the threads using the specified timeout.
|
public Sync()
2 threads.public Sync(int parties)
parties - the number of threads that must reach the synchronization point to
satisfy the barrierpublic void sync()
Barrier.getDefaultTimeout() as the timeout.public void sync(long millis)
millis - the timeout, in millisecondspublic void sync(long timeout,
TimeUnit units)
timeout - the timeoutunits - the unit of time in which the timeout is specifiedCopyright © 2017 Atlassian. All rights reserved.