多线程交替打印奇数偶数或者多线程交替打印ABC。本例中基于AtomicInteger 实现,也可以使用volatile关键字实现。
写一个demo实现多线程交替打印ABC,同理也可实现交替打印奇数偶数等;供小伙伴们参考
1 import java.util.concurrent.atomic.AtomicInteger; 2 3 public class ThreadDemo { 4 volatile static int count = 0; 5 static AtomicInteger atomicInteger = new AtomicInteger(0); 6 7 public static void main(String[] s) { 8 Thread t1 = new Thread(() -> { 9 while (true) { 10 if (atomicInteger.get() % 3 == 0) { 11 try { 12 Thread.sleep(1000L); 13 } catch (InterruptedException e) { 14 e.printStackTrace(); 15 } 16 System.out.println("A" + (atomicInteger.getAndIncrement()));//获取当前值并自增1 是原子操作(此处可用volatile 修饰的int 类型字段代替) 17 } 18 } 19 }); 20 21 Thread t2 = new Thread(() -> { 22 while (true) { 23 if (atomicInteger.get() % 3 == 1) { 24 try { 25 Thread.sleep(1000L); 26 } catch (InterruptedException e) { 27 e.printStackTrace(); 28 } 29 System.out.println("BB" + (atomicInteger.getAndIncrement())); 30 } 31 } 32 }); 33 34 Thread t3 = new Thread(() -> { 35 while (true) { 36 if (atomicInteger.get() % 3 == 2) { 37 try { 38 Thread.sleep(1000L); 39 } catch (InterruptedException e) { 40 e.printStackTrace(); 41 } 42 System.out.println("CCC" + (atomicInteger.getAndIncrement())); 43 } 44 } 45 }); 46 47 48 t1.start(); 49 t2.start(); 50 t3.start(); 51 } 52 }