关于多个线程操作同一变量遇到问题,求指教
我想实现多个线程对同一个变量进行累加,当某个线程发现这个变量超过指定值比如300,就在这个线程内部结束所有的线程运行,我写的代码如下,为什么运行的时候还是有些线程没有被结束掉呢?
private int flag = 0;
Thread[] threads = new Thread[20];
private object LockThis = new System.Object();
private void button4_Click(object sender, EventArgs e)
{
for (int i = 0; i < threads.Length; i++)
{
threads[i] = new Thread(new ParameterizedThreadStart(threadMethod));
threads[i].Start(i);
}
}
private void threadMethod(object n)
{
for (int i = 0; i < 100; i++)
{
lock (LockThis)
{
flag++;
Console.WriteLine( flag.ToString());
if (flag >= 300)
{
Console.WriteLine("线程"+n.ToString()+"检测到flag已经达到目标数值,自动终结所有线程");
foreach (Thread t in threads)
{
t.Abort();
}
}
}
}
}
实际运行的时候,是这样的,总有几个线程没有被结束掉:
。。。。。。
295
296
297
298
299
300
线程2已经达到目标数值,自动终结所有线程
301
线程3已经达到目标数值,自动终结所有线程
302
线程8已经达到目标数值,自动终结所有线程
上面的代码出问题在什么地方呢?除了上面的用Lock,还有什么更好的方法呢?