我的代码就像:
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(); } }
}
线程安全同步器搞得一团糟。这里有一些相当简单的代码,我希望得到如下输出:thread1,thread2,thread3和来自Runnable的消息, 但似乎存在竞争条件:
Three threads? Really?
Thread-4
Three threads? Really?
Thread-5
Thread-2
Thread-3
Thread-1
Thread-0
那么,我应该添加reentrantlock或其他什么来修复它吗?