我的代码是这样的:
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 还是其他什么来修复它?