日期:2014-05-17 浏览次数:20828 次
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Runtime.Remoting.Messaging;
namespace CLR_Thread
{
public class LockClass
{
public int i;
public LockClass(int n)
{
i = n;
}
}
class Program
{
private static readonly LockClass lockobj = new LockClass(3);
static void Main(string[] args)
{
Thread lockThd = new Thread(LockMethod);
lockThd.Start();
Thread.Sleep(2000);//让lockThd线程第一个执行,先lock lockobj
Thread useThd = new Thread(UseLockObj);//这个线程在lockobj锁定后,测试lockobj能否使用
useThd.Start();
}
static void UseLockObj()
{
Console.WriteLine(lockobj.i);
}
static void LockMethod()
{
lock (lockobj)
{
Console.WriteLine("lockobj is locked");
Thread.Sleep(10000);
}
}
}
}
{
//不被同时执行的代码
}