首先使用设计模式中的单件模式,防止多次初始化对象,造成访问空间的不一致。
计数处要加lock,将其他线程计数暂时阻塞,保证计数的正确性。
如果要想实时计数实时输出,可以将计数和输出处一并lock处理,不然不同线程的计数和输出结果未必按顺序处理,
如此加锁能保证按顺序处理按顺序输出,不过这样多少都 损失了一些性能
代码中加锁位置很重要
此程序会增加三次运算,原因是本线程未到200次,但是必然会有一个线程第一次增加所以在add里再做判断
复制代码 代码如下:
CommonSigleton MyCounter =CommonSigleton.Instance;
/// <summary>
/// 线程工作
/// </summary>
public void DoSomeWork()
{
///构造显示字符串
string results = "";
///创建一个Sigleton实例
System.Threading.Thread.Sleep(100);
int i = 0;
while (MyCounter.GetCounter() < 200)
{
//保证计数与输出一致,即便计数与输出之间加上时间间隔也会为这块区域加锁,防止其他线程操作
lock (this)
{
///开始计数
MyCounter.Add();
System.Threading.Thread.Sleep(100);
Thread thread = Thread.CurrentThread;
results += "线程";
results += i++.ToString() + "——〉" + thread.Name + " ";
results += "当前的计数:";
results += MyCounter.GetCounter().ToString();
results += "n";
Console.WriteLine(results);
// 清空显示字符串
results = "";
}
}
}
public void StartMain()
{
Thread thread0 = Thread.CurrentThread;
thread0.Name = "Thread 0";
Thread thread1 =new Thread(new ThreadStart(DoSomeWork));
thread1.Name = "Thread 1";
Thread thread2 =new Thread(new ThreadStart(DoSomeWork));
thread2.Name = "Thread 2";
Thread thread3 =new Thread(new ThreadStart(DoSomeWork));
thread3.Name = "Thread 3";
thread1.Start();
thread2.Start();
thread3.Start();
///线程0也只执行和其他线程相同的工作
DoSomeWork();
}
}