线程内存共享冲突
class Class1
{
    public int i = 5;
    public void Cooo() {
        this.i++;
        if (this.i == 5) {
            Console.WriteLine("我可能会被输出");
        }

        this.i = 5;
    }
}

static void CallFunc(object obj) {
    Class1 o = obj as Class1;
    while (true) {
        o.Cooo();
    }
}

Class1 c = new Class1();
Thread go1 = new Thread(CallFunc);
go1.Start(c);
Thread go2 = new Thread(CallFunc);
go2.Start(c);


此时,“我可能会被输出”真的会输出

从程序设计来看,这句话是不可能被输出的

但是,这里开启两个线程后,共享了这份内存

时间线变成了两条,不在是顺着,有可能在i++之后,另一个线程修改i=5,此时再到回到这个线程,判断i确实=5


首页 我的博客
粤ICP备17103704号