usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;namespace _20211014线程资源竞争加锁
{classProgram{staticvoidMain(string[] args){MyClass o =newMyClass();Thread t1 =newThread(func01);
t1.Start(o);//启动t2:newThread(func01).Start(o);
Console.ReadKey();}staticvoidfunc01(object o){MyClass my = o asMyClass;while(true){lock(my)//锁定对象资源{
my.SetI();//修改竞争到的资源}//释放锁}}}}
资源类
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespace _20211014线程资源竞争加锁
{classMyClass{privateint i =5;publicvoidSetI(){
i++;if(i==5){
Console.WriteLine("i此时等于5");}
i =5;//Console.WriteLine("--------------------");}}}