Lock方法的用途。
不使用Lock方法:
namespace ConsoleApplication1
{
class Program
{
//static object alock;
static List<int> l = new List<int>();
static void Main(string[] args)
{
Thread t1 = new Thread(threadwork1);
Thread t2 = new Thread(threadwork2);
t1.Start();
t2.Start();
while (t1.IsAlive || t2.IsAlive)//等待2个线程都运行完毕
{
Console.WriteLine("t1 or t2 are still alive");
Thread.Sleep(0);
}
for (int i = 0; i < l.Count; i++)
{
Console.WriteLine(l[i]);
}
}
static void threadwork1()
{
for (int i = 0; i < 1000000; i++)
{
if (i % 50000 == 0)
l.Add(i/1000);
}
}
static void threadwork2()
{
for (int i = -1; i > -1000000; i--)
{
if (i %50000 == 0)
l.Add(i/1000 );
}
}
}
}
输出结果为正负交替。根据cpu运行速度自行调节循环次数。
使用Lock锁的话,则先是正数全部加载完毕,再加载负数。
本文转自cnn23711151CTO博客,原文链接:http://blog.51cto.com/cnn237111/510245 ,如需转载请自行联系原作者