多线程<公共数据的访问一>

使用多线程时常会出现各种奇怪的问题,死锁、异常或是公共数据的安全性。今天我就遇到了一个多线程中有关公共数据安全性的问题。

代码如下:

View Code
 1 publicclass Class1 {
2
3 privatestaticbool ISCONN =false;
4
5 ///<summary>
6 /// 如果线程未被开启,就启动一个新线程,该线程将会在1000ms后被执行
 7 ///</summary>
8 publicstaticvoid StartNewTread()
9 {
10 if (!ISCONN)
11 {
12 new System.Threading.Thread(() =>
13 {
14 System.Threading.Thread.Sleep(1000);
15 ISCONN =true;
16 while (ISCONN)
17 {
18 //TO-DO
19 }
20 }).Start();
21 }
22 }
23
24 ///<summary>
25 /// 正常终止线程。
26 ///</summary
27 public static void BreakOff() { ISCONN = false; }
28 }

表面上看这段代码似乎并没有问题,但是事实并非如此。

问题代码:

View Code
14                     System.Threading.Thread.Sleep(1000);
15 ISCONN =true;

上面代码的问题就出在,如果用户在线程休眠期间通过BreakOff()方法修改了ISCONN=false,那么该修改将会是无效的修改,因为ISCONN将会在1000ms后重新被修改为ture。

View Code
 1 publicclass Class1 {
2
3 privatestaticbool ISCONN =false;
4
5 ///<summary>
6 /// 如果线程未被开启,就启动一个新线程
7 ///</summary>
8 publicstaticvoid StartNewTread()
9 {
10 if (!ISCONN)
11 {
12 new System.Threading.Thread(() =>
13 {
14 ISCONN =true;
15 System.Threading.Thread.Sleep(1000);
16 while (ISCONN)
17 {
18 //TO-DO
19 }
20 }).Start();
21 }
22 }
23
24 ///<summary>
25 /// 正常终止线程。
26 ///</summary
27 public static void BreakOff() { ISCONN = false; }
28 }

 上面看似只是两行代码颠倒的问题,而且问题只存在于间隔在1s之内发生的开启与结束线程的操作,但是它却是错误的,这正印了那条著名的“墨菲定律”--事情如果有变坏的可能,不管这种可能性有多小,它总会发生

原文地址:https://www.cnblogs.com/tao_/p/2121173.html