同步不适用于循环屏障
Synchronized does not work by cyclic barrier
public class Test {
final int counter = 0; // it may be a different number
int add = 0;
public synchronized void testSync() throws InterruptedException {
add++;
if (add == counter) {
add = 0;
notifyAll();
} else {
while (add > 0) {
wait();
}
}
}
}
如何修复代码以使其工作?我需要使其作为循环屏障工作。
public class Test {
final int counter = 0; // it may be a different number
final CyclicBarrier barrier = new CyclicBarrier(counter);
public void testSync() throws InterruptedException, BrokenBarrierException {
barrier.await();
}
}
public class Test {
final int counter = 0; // it may be a different number
int add = 0;
public synchronized void testSync() throws InterruptedException {
add++;
if (add == counter) {
add = 0;
notifyAll();
} else {
while (add > 0) {
wait();
}
}
}
}
如何修复代码以使其工作?我需要使其作为循环屏障工作。
public class Test {
final int counter = 0; // it may be a different number
final CyclicBarrier barrier = new CyclicBarrier(counter);
public void testSync() throws InterruptedException, BrokenBarrierException {
barrier.await();
}
}