Skip to content

Instantly share code, notes, and snippets.

@Normal
Created June 16, 2017 15:59
Show Gist options
  • Save Normal/f702bb7d9b4c462d27d100c97e8740c1 to your computer and use it in GitHub Desktop.
Save Normal/f702bb7d9b4c462d27d100c97e8740c1 to your computer and use it in GitHub Desktop.
package com.example.demo;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclingBarrierExample {
private static final CyclicBarrier BARRIER = new CyclicBarrier(3, new FerryBoat());
public static void main(String[] args) throws InterruptedException {
for (int i = 1; i <= 9; i++) {
new Car(i).start();
Thread.sleep(600L);
}
}
static class FerryBoat implements Runnable {
@Override
public void run() {
try {
Thread.sleep(500L);
System.out.println("... Ferry transferring ...");
} catch (InterruptedException ignored) {
}
}
}
static class Car extends Thread {
private int number;
Car(int number) {
this.number = number;
}
@Override
public void run() {
System.out.println(number + " car is ready to transfer");
try {
BARRIER.await();
} catch (InterruptedException | BrokenBarrierException ignored) {
}
System.out.println(number + " car is successfully transferred");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment