首页 > 代码库 > 关于多线程实例运用

关于多线程实例运用

一、

class ThreadParam
{
public int ThreadID { get; set; }
public ManualResetEvent MSE { get; set; }
}

 

二、

static void Main(string[] args)
{



List<ThreadParam> list = new List<ThreadParam>();
Stopwatch watcher = new Stopwatch();
watcher.Start();
for (int i = 0; i < 5; i++)
{
ThreadParam tp = new ThreadParam();
tp.ThreadID = i;
tp.MSE = new ManualResetEvent(false);
Thread t = new Thread(new ParameterizedThreadStart(ThreadVoid));
t.IsBackground = true;
t.Start(tp);
list.Add(tp);
}
foreach (ThreadParam tp in list)
{
tp.MSE.WaitOne();
}
watcher.Stop();

Console.WriteLine("总用时:" + watcher.ElapsedMilliseconds.ToString() + "ms");
Console.ReadLine();
}

三、

static void ThreadVoid(object o)
{
ThreadParam tp = (ThreadParam)o;
Stopwatch watcher = new Stopwatch();
watcher.Start();
Console.WriteLine("线程" + tp.ThreadID.ToString() + ":开始");
Thread.Sleep(5000);
watcher.Stop();
Console.WriteLine("线程" + tp.ThreadID.ToString() + ":结束,用时" + watcher.ElapsedMilliseconds.ToString() + "ms");
tp.MSE.Set();
}

关于多线程实例运用