您的位置:首页 > 其它

多线程简单应用示例

2013-12-31 15:18 316 查看
程序主题部分摘自msdn中Thread 类的示例说明,地址:http://msdn.microsoft.com/zh-cn/library/System.Threading.Thread(v=vs.110).aspx

附改动后的代码:

主体代码:

static void Main(string[] args)
{
Console.WriteLine("Main thread: Start a second thread.");

List<Thread> listT = new List<Thread>();

for (int i = 0; i < 5; i++)
{
Thread t = new Thread(new ThreadStart(ThreadProc));

listT.Add(t);

t.Start();
//Thread.Sleep(0);
}

for (int i = 0; i < 4; i++)
{
Console.WriteLine("Main thread: Do some work.");
Thread.Sleep(0);
}

Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.");
foreach (Thread t in listT)
{
t.Join();
}
Console.WriteLine("Main thread: ThreadProc.Join has returned.  Press Enter to end program.");
Console.ReadLine();
}

public static void ThreadProc()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("ThreadProc: {0}", i);
// Yield the rest of the time slice.
Thread.Sleep(0);
}
}


需要单独控制线程停止,可给线程设置Name属性来实现。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: