Site Search:

ThreadGate.java

 ThreadGate.java

/**
* ThreadGate
* <p/>
* Recloseable gate using wait and notifyAll
*/
public class ThreadGate {
// CONDITION-PREDICATE: opened-since(n) (isOpen || generation>n)
private boolean isOpen;
private int generation;

public synchronized void close() {
isOpen = false;
}

public synchronized void open() {
++generation;
isOpen = true;
notifyAll();
}

// BLOCKS-UNTIL: opened-since(generation on entry)
public synchronized void await() throws InterruptedException {
int arrivalGeneration = generation;
while (!isOpen && arrivalGeneration == generation)
wait();
// while (!isOpen)
// wait();
System.out.println(arrivalGeneration + " " + generation);
}

public static void main(String...args) {
ThreadGate tg = new ThreadGate();
for(int i = 0; i < 100; i++) {
int ii = i;
new Thread(() -> {
try {
tg.await();
System.out.println("finish run thread "+ii);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}

System.out.println("initiated all the threads");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}

for(int i = 0; i < 100; i++) {
tg.open();
tg.close();
}
}
}

The ThreadGate class implements a reclosable barrier using intrinsic synchronization with wait() and notifyAll(). It allows threads to wait until a gate is explicitly opened, and once opened, all threads that arrived before or during the opening are allowed to proceed. Each opening is associated with a new generation count, enabling the gate to distinguish between different open-close cycles. The await() method blocks until the gate is open and the generation has advanced, ensuring that threads respond only to openings after they arrived. This design supports repeated gating behavior, unlike one-time latches, and is useful in staged concurrent processing or coordination barriers. The main() method demonstrates how 100 threads wait on the gate, and each is released one by one as the gate is opened and closed in a loop.

No comments:

Post a Comment