多线程技术(三)一个多线程程序
使用两个线程显示计数。
该示例的核心是方法DisplayNumbers(),它累加一个数字,并定期显示每次累加的结果:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ConsoleThread { class ThreadApp { static int interval; static void DisplayNumbers() { //获取当前运行线程的Thread对象的实例 Thread thisThread = Thread.CurrentThread; Console.WriteLine("线程:" + thisThread.Name + "已开始运行."); //循环计数直到结束,在指定的间隔输出当前计数值 for (int i = 1; i <= 8 * interval; i++) { if (i % interval == 0) { Console.WriteLine(thisThread.Name + ":当前计数为" + i); } } Console.WriteLine("线程" + thisThread.Name + "完成."); } static void Main(string[] args) { //获取用户输入的数字 Console.Write("请输入一个数字:"); interval = int.Parse(Console.ReadLine()); //定义当前主线程对象的名字 Thread thisThread = Thread.CurrentThread; // thisThread.Priority = ThreadPriority.Lowest; thisThread.Name = "Main Thread"; //建立新线程对象 ThreadStart workerStart = new ThreadStart(DisplayNumbers); Thread workerThread = new Thread(workerStart); workerThread.Name = "Worker Thread"; workerThread.Priority = ThreadPriority.AboveNormal; workerThread.IsBackground = true; workerThread.Start(); //启动新线程 DisplayNumbers(); //主线程同步进行计数 Console.ReadKey(); } } }