2年大厂经验,面试还是太紧张,90%的人不会写

public class MultiThreadPrintTest {
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(3);
AtomicInteger count = new AtomicInteger(0);
CompletableFuture.runAsync(() -> {
while (true) {
// 自旋等待
while (count.get() % 2 != 0 ) {
}
if (count.get() < 100) {
System.out.println("a");
count.getAndIncrement();
} else {
try {
// 让另一个线程最后的自旋解锁
count.getAndIncrement();
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
throw new RuntimeException(e);
}
return;
}
}
});
CompletableFuture.runAsync(() -> {
while (true) {
// 自旋等待
while (count.get() % 2 != 1 ) {
}
if (count.get() < 100) {
System.out.println("b");
count.getAndIncrement();
} else {
try {
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
throw new RuntimeException(e);
}
return;
}
}
});
try {
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
throw new RuntimeException(e);
}
System.out.println("执行结束");
}
}