C#多线程的用法1-简单示例
写在前面:阅读本系列文章即表示你已经知道什么是线程等理论知识,现在正想了解如何正确的使用线程进行编程工作。
/// <summary> /// 单线程工作示例 /// </summary> private static void SingleThreadDemo() { Console.WriteLine("Main Thread"); Thread thread = new Thread(() => { for (var i = 0; i < 10; i++) { Console.WriteLine(String.Format("Thread Out:{0}", i)); Thread.Sleep(500); } Console.WriteLine("Sub Thread The End"); }); thread.Start(); Console.WriteLine("Main Thread Wait For Sub Thread"); } /// <summary> /// 多个线程工作示例 /// </summary> private static void MultiThreadDemo() { ThreadStart task = () => { for (var i = 0; i < 10; i++) { Console.WriteLine(String.Format("Thread {0} Out:{1}", Thread.CurrentThread.Name, i)); Thread.Sleep(500); } Console.WriteLine(String.Format("Sub Thread {0} The End", Thread.CurrentThread.Name)); }; Console.WriteLine("Main Thread"); Thread thread1 = new Thread(task) { Name = "thread1" }; thread1.Start(); Thread thread2 = new Thread(task) { Name = "thread2" }; thread2.Start(); Thread thread3 = new Thread(task) { Name = "thread3" }; thread3.Start(); Console.WriteLine("Main Thread Wait For Sub Thread"); } static void Main(string[] args) { //SingleThreadDemo(); //MultiThreadDemo(); Console.ReadLine(); }
作者:DW039
出处:http://www.cnblogs.com/dw039
本文由DW039原创并发布于博客园,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。