交替打印出奇数和偶数

两个线程如何交替打印出奇数和偶数

分析

两个线程交替打印奇数和偶数,最关键的是如何协作的问题。

  • 打印的数可以用java里面的atomicInteger 来保证原子性;
  • 打印何时结束需要设置一个上限,比如打印到100结束;
 1 public class PrintABAtomic{
 2     private static final int MAX_PRINT_NUM = 100;
 3     private static final AtomicInteger atomicInteger = new AtomicInteger(0);
 4 
 5     public void printAB(){
 6         new Thread(() -> {
 7             while (atomicInteger.get() < MAX_PRINT_NUM){
 8                 //打印奇数
 9                 if(atomicInteger.get() % 2 == 0){
10                     //log.info("num:" + atomicInteger.get());
11                     System.out.println("num:" + atomicInteger.get());
12                     atomicInteger.incrementAndGet();
13                 }
14             }
15         }).start();
16 
17         new Thread(() -> {
18             while (atomicInteger.get() < MAX_PRINT_NUM) {
19                 // 打印偶数.
20                 if (atomicInteger.get() % 2 == 1) {
21                     //log.info("num:" + atomicInteger.get());
22                     System.out.println("num:" + atomicInteger.get());
23 
24                     atomicInteger.incrementAndGet();
25                 }
26             }
27         }).start();
28     }

 还可以采用另一种办法。用volatile 的方式来实现。

 1 public class PrintABVolatile {
 2     private static final int MAX_VALUE_NUM = 100;
 3     private static volatile int count = 0;
 4 
 5 
 6     public void printAB(){
 7         new Thread(() -> {
 8             while(count < MAX_VALUE_NUM){
 9                 if(count % 2 == 0){
10                     System.out.println("偶数线程num" + count);
11                     count++;
12                 }
13             }
14         }).start();
15         new Thread(() -> {
16             while(count < MAX_VALUE_NUM){
17                 if(count % 2 == 1){
18                     System.out.println("奇数线程num" + count);
19                     count++;
20                 }
21             }
22         }).start();
23     }
24 }

直接用main方法调试

当然,这种方法仅用于调试,不能用于写单元测试。

1 public class TestRunner {
2     public static void main(String[] args) {
3         /*PrintABAtomic printABAtomic = new PrintABAtomic();
4         printABAtomic.printAB();*/
5         PrintABVolatile printABVolatile = new PrintABVolatile();
6         printABVolatile.printAB();
7     }
8 }

提供了两种方法,分别利用volatile的可见性和AtomicInteger 的原子性对两个线程进行协调。

原文地址:https://www.cnblogs.com/xujiangxi/p/12364734.html