首页 > 代码库 > 线程并发和异步
线程并发和异步
class Program { //主线程 static void Main(string[] args) { StartThreads(); Console.ReadKey(); } public static void StartThreads() { Stopwatch watch = new Stopwatch(); watch.Start(); Thread t1 = new Thread(Print1); t1.Name = "Thread1"; Thread t2 = new Thread(Print1); t2.Name = "Thread2"; Thread t3 = new Thread(Print1); t3.Name = "Thread3"; //启动3个新的线程(同时执行Print1操作,属于并发行为) t1.Start(); t2.Start(); t3.Start(); //注释掉线程Join方法,对主线程的后续程序来说存在异步行为 //t1.Join(); //t2.Join(); //t3.Join(); Console.Write(watch.Elapsed); watch.Restart(); Print2(); Console.Write(watch.Elapsed); } public static void Print1() { for (int i = 0; i < 1000; i++) { Console.WriteLine(Thread.CurrentThread.Name+":"+i); } } public static void Print2() { for (int i = 0; i < 3000; i++) { Console.WriteLine(i); } } }
线程并发和异步
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。