public class CyclicBar {
private final static CyclicBarrier cb = new CyclicBarrier(3,
new Runnable() {
@Override
public void run() {
System.out.println("\n-------------");
}
});
public static void main(String[] args) {
final class ColouredRunnable implements Runnable {
private int i;
public ColouredRunnable(int j) {
this.i = j;
}
@Override
public void run() {
final String name = Thread.currentThread().getName();
while (true) {
cyclicAwait();
for (int i = 0; i < name.length(); i++) {
sleep();
// System.out.print("" + name.charAt(i) + this.i + " ");
System.out.print("" + name.charAt(i) + " ");
}
}
}
}
;
int i = 0;
new Thread(new ColouredRunnable(i++), "RED").start();
new Thread(new ColouredRunnable(i++), "BLUE").start();
new Thread(new ColouredRunnable(i++), "GREEN").start();
}
private static int cyclicAwait() {
try {
return cb.await();
} catch (InterruptedException | BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return -1;
}
private static void sleep() {
try {
Thread.sleep(ThreadLocalRandom.current().nextLong(200, 600));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
上面的代码当前打印
-------------
G R B R E L E E D U E N
-------------
B R G E R L U E D E E N
-------------
R G B E L R E U D E E N
-------------
R G B E R L U E D E E N
-------------
B R G E L D R U E E E N
-------------
如何更改上述代码并在适当的位置添加适当的屏障以产生以下输出
-------------
R E D B L U E G R E E N
-------------
R E D B L U E G R E E N
-------------
R E D B L U E G R E E N
约束
- 必须使用现代 Java 并发更高级别的对象之一
- 不应使用隐式锁定
synchronised
wait
notify
- 必须使用 System.out.print() 打印单个字符
- 使用 3 个线程,每个线程必须打印其名称(颜色)
- 应按 RED BLUE GREEN 的顺序打印