欢迎光临散文网 会员登陆 & 注册

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

2023-07-02 16:59 作者:烈灬火5  | 我要投稿

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("执行结束");

  }

}

2年大厂经验,面试还是太紧张,90%的人不会写的评论 (共 条)

分享到微博请遵守国家法律