public class ThreadInteroperateWithLock
{
private int m_count;
private object m_synLock;
public ThreadInteroperateWithLock()
{
m_count = 0;
m_synLock = new object();
} public int Count { get { return m_count; } } public void Add()
{
lock (this)
{
m_count++;
}
}
}ThreadInteroperateWithLock ope = new ThreadInteroperateWithLock();
Thread[] threadArray = new Thread[100];
for (int i = 0; i < 100; i++)
{
Thread thread = new Thread(new ThreadStart(ope.Add));
thread.IsBackground = false;
threadArray[i] = thread;
}
for (int i = 0; i < 100; i++)
{
threadArray[i].Start();
}
Console.WriteLine(ope.Count);
Console.ReadKey();输出还是不稳定,是不是我的代码没有对?
{
private int m_count;
private object m_synLock;
public ThreadInteroperateWithLock()
{
m_count = 0;
m_synLock = new object();
} public int Count { get { return m_count; } } public void Add()
{
lock (this)
{
m_count++;
}
}
}ThreadInteroperateWithLock ope = new ThreadInteroperateWithLock();
Thread[] threadArray = new Thread[100];
for (int i = 0; i < 100; i++)
{
Thread thread = new Thread(new ThreadStart(ope.Add));
thread.IsBackground = false;
threadArray[i] = thread;
}
for (int i = 0; i < 100; i++)
{
threadArray[i].Start();
}
Console.WriteLine(ope.Count);
Console.ReadKey();输出还是不稳定,是不是我的代码没有对?
解决方案 »
- 问个C# DataGridView的,怎样选中CheckBox
- 急求!!大家来看看,这段程序有什么问题,为什么点击button没有反应呢??
- 有什么软件能生成intermec打印机的 IPL文件吗
- 【在线等】关于 引用类型的弱智问题
- 在线急求正则表达式
- 如何将日期输入为[Thu, 14 Dec 2006 16:21:22 +0800]格式
- 怎样用C#代码实现从SQL_server中定时导出数据,数据格式是文本文件?(在线等)
- C#和ASP.NET到底是什么关系啊?C#是不是主要用来开发ASP.NET网页程序的啊?我想学网页制作,到底是学ASP.NET还是学C#啊?
- SQL的問題
- 谁能给一个用delphi写的Dll的例子。能让C#调用的?
- show一个窗体时,如何用屏幕坐标来定位窗体的位置呢?
- 学ASP。net的“被”winform去了,以后会怎样。
private static ThreadInteroperateWithLock clone = null;
............
if (clone == null)
{
lock (m_synLock)
{
clone=Nested.Clone;
m_count++;
}
} class Nested///嵌套类延时实例化。
{
static Nested()
{
}
internal static readonly ThreadInteroperateWithLockClone = new ThreadInteroperateWithLock();
}
而且你可以试试把m_synLock替换上去,貌似还是有问题。
{
lock (m_synLock)
{
m_count++;
}
}
你的lock里面用的this。这里是一个对象。如果这个类再次被实例化,那么检测不到之前实例化的对象被Lock了。
所以不起作用。简单的办法就是lock一个静态对象。
The problem here would be that you're kicking off the threads and they're not entirely finished by the time of your call to write output to the console.The loop starts off i threads, we'll imagine these as bees going of collecting as work, not all going to the same food source so some take longer to return than others; then, back at the hive, we suddenly say: "Hey, bees, I need a headcount!", "...1, 2, 3..., only three?" No, some i-3 are still scrounging around outside!So, the idea is that we must have an indicator of when work is completed, or a homing signal of sorts to get all bees back to the hive for the headcount. This can be done with Join, or manual state checking (which essentially has you holding out until the last sojourner returns.)