对static变量,做lock时。可以通过lock(typeof(classname))来锁定该变量所在的类的类型,达到线程同步的目的。测试代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Windows.Forms;
using System.Threading;
namespace ConsoleApplication1
{
class xx
{
public static int a = 0;
}
class Program
{
private Object thislock = new Object();
public void test1()
{
lock (typeof(xx))
{
for (int i = 1; ; i++)
{
if (xx.a > i)
{
MessageBox.Show("c=" + xx.a + "\ti=" + i);
break;
}
xx.a = i;
Console.WriteLine("test1 " + xx.a);
}
}
}
public void test2()
{
lock (typeof(xx))
{
xx.a += 2;
Console.WriteLine("test2 " + xx.a);
}
}
static void Main(string[] args)
{
Program pth1 = new Program();
Program pth2 = new Program();
Thread thr1 = new Thread(pth1.test1);
Thread thr2 = new Thread(pth2.test2);
System.Timers.Timer time = new System.Timers.Timer();
time.Interval = 1000;
thr1.Start();
time.Enabled = true;
thr2.Start();
}
}
}
thr1和thr2同时访问static变量a,由于xx进程被锁定thr2只能等待。