简介

使用 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;
        }
    }
}
posted on 2021-07-05 16:56  HDU李少帅  阅读(128)  评论(0编辑  收藏  举报