多线程交替实现打印奇偶数Java代码

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class Xiancheng {
  private static AtomicInteger num = new AtomicInteger(0);//原子操作类(:自增减的使用)
  private static CountDownLatch countDownLatch = new CountDownLatch(2);//需两次调用countDown方法才唤醒阻塞进程
  @Test
  public void test() throws InterruptedException {
    new Thread(() -> {//lambda表达式(new run()…)
      while (num.intValue() < 10) {
        if (num.intValue() % 2 != 0 ) {
          System.out.println(“奇数:” + num);
          num.incrementAndGet();//自增的原子操作保证
         }
       }
     countDownLatch.countDown();
     }).start();
     new Thread(() -> {
      while (num.intValue() <= 10) {
        if (num.intValue() % 2 == 0) {
           System.out.println(“偶数:” + num);
          num.incrementAndGet();//自增的原子操作保证
         }
       }
       countDownLatch.countDown();
     }).start();
     countDownLatch.await();//能够阻塞线程
  }
}

你可能感兴趣的:(多线程交替实现打印奇偶数Java代码)