各位牛友,帮忙看看这个并发的结果为什么是0呀

public class ThreadTest {
    private volatile static int count=0;
    private volatile static int flag=0;
    private static void add(){
        for(int i=0;i<1e7;i++){
            count=count+1;
        }
    }
    public static void main(String[] args) {
        Thread t1=new Thread(new Runnable() { @Override public void run() {
                //lock
                while(flag==1){
                    System.out.print(".");
                }
                flag=1;
                //临界区
                add();
                //unlock
                flag=0;
            }
        });
        Thread t2=new Thread(new Runnable() { @Override public void run() {
                //lock
                while(flag==1){
                    System.out.print(".");
                }
                flag=1;
                //临界区
                add();
                //unlock
                flag=0;
            }
        });
        t1.start();
        t2.start();
        System.out.println(count);
    }
}

#Java#
全部评论
我大概知道了,我的测试与设置写法不是原子的
点赞 回复 分享
发布于 2021-01-15 04:26
最后输出count前加个sleep(1)你就知道了
点赞 回复 分享
发布于 2021-01-14 23:51

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务