java 两个线程交替打印到100

简介

使用 volatile

code

/**
 * Created by lee on 2021/7/5.
 */
public class Counter {
    static volatile int flag = 0;
    public static void main(String[] args){
        new Thread(new Task1(),"A").start();
        new Thread(new Task2(),"B").start();
    }
}

class Task1 implements Runnable{
    @Override
    public void run(){
        int i = -2;
        while(i<=99){
            while(Counter.flag == 1);
            i+=2;
            System.out.println("a:" + i);
            Counter.flag = 1;
        }
    }
}

class Task2 implements Runnable{
    @Override
    public void run(){
        int i = -1;
        while(i<=98){
            while(Counter.flag == 0);
            i+=2;
            System.out.println("b:" + i);
            Counter.flag = 0;
        }
    }
}
Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/14973218.html