Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Demonstration {
- public static void main(String[] args) throws Exception {
- CyclicBarrier.runTest();
- }
- }
- class CyclicBarrier {
- public static void runTest() throws InterruptedException {
- CyclicBarrier barrier = new CyclicBarrier(3);
- Thread t1 =
- new Thread(
- new Runnable() {
- @Override
- public void run() {
- try {
- System.out.println("T1");
- barrier.await();
- // Thread 1 will be blocked on the barrier so won't be reaching here until
- // previous barrier is cleared.
- System.out.println("T1");
- barrier.await();
- System.out.println("T1");
- barrier.await();
- } catch (InterruptedException ie) {
- }
- }
- });
- Thread t2 =
- new Thread(
- () -> {
- try {
- Thread.sleep(500);
- System.out.println("T2");
- barrier.await();
- Thread.sleep(500);
- System.out.println("T2");
- barrier.await();
- Thread.sleep(500);
- System.out.println("T2");
- barrier.await();
- } catch (InterruptedException ie) {
- }
- });
- Thread t3 =
- new Thread(
- () -> {
- try {
- Thread.sleep(1000);
- System.out.println("T3");
- barrier.await();
- Thread.sleep(1000);
- System.out.println("T3");
- barrier.await();
- Thread.sleep(1000);
- System.out.println("T3");
- barrier.await();
- } catch (InterruptedException ie) {
- }
- });
- t1.start();
- t2.start();
- t3.start();
- t1.join();
- t2.join();
- t3.join();
- }
- private int threadsToWaitFor;
- private int threadsWaiting = 0;
- private int threadsToRelease = 0;
- public CyclicBarrier(int threadsToWaitFor) {
- this.threadsToWaitFor = threadsToWaitFor;
- }
- public synchronized void await() throws InterruptedException {
- // No new thread is allowed for a new Barrier until we have reset the current barrier.
- while (threadsWaiting == threadsToWaitFor) {
- wait();
- }
- threadsWaiting++;
- // All threads have reached the barrier.
- if (threadsWaiting == threadsToWaitFor) {
- threadsToRelease = threadsToWaitFor;
- // Notify remaining threads who have already reached the barrier.
- notifyAll();
- } else {
- // Wait for all the threads to arrive at the barrier.
- while (threadsWaiting < threadsToWaitFor) {
- wait();
- }
- }
- // We freed up the current thread.
- threadsToRelease--;
- // If this is the last thread to be freed up, we can reset the barrier.
- if (threadsToRelease == 0) {
- threadsWaiting = 0;
- // New threads might have attempted for a new barrier, we want to notify them.
- notifyAll();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement