2年大廠經(jīng)驗,面試還是太緊張,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("執(zhí)行結(jié)束");
??}
}