多线程计数,怎么保持计数准确的方法
首先使用设计模式中的单件模式,防止多次初始化对象,造成访问空间的不一致。
计数处要加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();
}
}
上一篇: java中Scanner类的简单用法分享