第三种方式,使用volatile标记
来源:7-7 交替打印

朝夕_
2020-01-07
第三种方式,使用volatile做一个标记
写回答
1回答
-
朝夕_
提问者
2020-01-07
/** * 使用两个线程交替打印 0-100 * volatile 标记实现 * @author xxx * @date 2020/1/7 16:05 */ public class Question3 { private static volatile boolean flag = true; private static int count = 0; private static int total = 100; public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { while (count <= total) { if (flag) { System.out.println("线程:" + Thread.currentThread().getName() + " => " + count ++); flag = false; } } } }, "偶数").start(); new Thread(new Runnable() { @Override public void run() { while (count <= total) { if (!flag) { System.out.println("线程:" + Thread.currentThread().getName() + " => " + count ++); flag = true; } } } }, "奇数").start(); } }
332020-05-09
相似问题