一、不加锁,多个线程同时执行时,导致资源冲突
![](https://images0.cnblogs.com/blog2015/35158/201505/132147322201807.png)
Thread t1 = new Thread(ThreadTest.ThreadNotThread); Thread t2 = new Thread(ThreadTest.ThreadNotThread); Thread t3 = new Thread(ThreadTest.ThreadNotThread); Thread t4 = new Thread(ThreadTest.ThreadNotThread); t1.Start(); t2.Start(); t3.Start(); t4.Start(); Console.ReadLine(); class ThreadTest { public static int num = 10; /// <summary> /// 线程未加锁,导致读取资源异常 /// 多个线程并行执行 /// </summary> public static void ThreadNotThread() { while (true) { if (num > 0) { Thread.Sleep(1000); Console.WriteLine("nums:" + num--); } } } }
二、加锁,多个线程同时执行时,依次执行,不会导致资源冲突
Thread t2 = new Thread(ThreadTest.ThreadSyncThread); Thread t3 = new Thread(ThreadTest.ThreadSyncThread); Thread t4 = new Thread(ThreadTest.ThreadSyncThread); t1.Start(); t2.Start(); t3.Start(); t4.Start(); class ThreadTest { public static int num = 10; /// <summary> /// 线程加锁,导致读取资源正常 /// 一个线程一个线程的执行 /// lock("")这里的""表示一个对象,每个对象都存在一个标志位,0和1,一个线程运行同步块时先检查对象标志位 /// 如果为0则表明同步块中存在其它线程在运行。这是该线程就处于就绪状态,直到处于同步块中的线程执行完成为止 /// </summary> public static void ThreadSyncThread() { while (true) { lock ("") { if (num > 0) { Thread.Sleep(1000); Console.WriteLine("nums:" + num--); } } } } }