My code is like:
public class Test {
final static CyclicBarrier CYCLIC_BARRIER = new CyclicBarrier(3, newRunnable() {
@Override
public void run() {
System.out.println("Correctly three?Really?");
}
});
public static void main(String[] args) {
for (int i = 0; i <6 ; i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
CYCLIC_BARRIER.await();
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}).start(); } }
}
Got some mess about threadsafe synchronizers. Some fairly simple code here, and I want to get output like: thread1,thread2,thread3 and the message from Runnable, but it seems there is a race condition:
Three threads? Really?
Thread-4
Three threads? Really?
Thread-5
Thread-2
Thread-3
Thread-1
Thread-0
So,should I add reentrantlock or whatever to fix it?