110,533
社区成员
发帖
与我相关
我的任务
分享
private void btnTest_Click(object sender, EventArgs e)
{
TestManyThread test = new TestManyThread();
test.Start();
}
class TestManyThread
{
private static DateTime lastOperyTime = DateTime.Now;
private static object lockTime = new object();
public static DateTime LastOperyTime
{
get
{
lock (lockTime)
{
return TestManyThread.lastOperyTime;
}
}
set
{
lock (lockTime)
{
TestManyThread.lastOperyTime = value;
}
}
}
public void Start()
{
for (int i = 0; i < 10; i++)
{
Thread th = new Thread(new ThreadStart(DoSomeThing));
th.Name = i.ToString();
th.SetApartmentState(ApartmentState.MTA);
th.IsBackground = true;
th.Start();
}
}
/// <summary>
/// 多个线程 做同一件事件 但是要求每一个线程做同一件事件之间有毫秒级的间隔
/// </summary>
private void DoSomeThing()
{
TimeSpan sp = DateTime.Now.Subtract(LastOperyTime);
int intervalTime = 100;//2个线程之间的间隔时间 毫秒
if (sp.TotalMilliseconds < intervalTime)
{
System.Threading.Thread.Sleep(intervalTime);
}
LastOperyTime = DateTime.Now;
string info = string.Format("线程ID:{0},执行时间:{1}"
, Thread.CurrentThread.Name, DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss:ffff"));
Console.WriteLine(info);
}
}