發布時間:2020-12-08 11:39 作者:獨孤劍 閱讀:2590
static void Main(string[] args) { Thread thread1 = new Thread(new ThreadStart(Test1)); thread1.Start(); thread1.Join(); Thread thread2 = new Thread(new ThreadStart(Test2)); thread2.Start(); thread2.Join(); Console.WriteLine("finished."); Console.Read(); } static void Test1() { Console.WriteLine("t1 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); Console.WriteLine("t1 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); Console.WriteLine("t1 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); Console.WriteLine("t1 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); Console.WriteLine("t1 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); Console.WriteLine("t1 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); Console.WriteLine("t1 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); Console.WriteLine("t1 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); Console.WriteLine("t1 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); Console.WriteLine("t1 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); } static void Test2() { Console.WriteLine("t2 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); Console.WriteLine("t2 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); Console.WriteLine("t2 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); Console.WriteLine("t2 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); Console.WriteLine("t2 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); Console.WriteLine("t2 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); Console.WriteLine("t2 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); Console.WriteLine("t2 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); Console.WriteLine("t2 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); Console.WriteLine("t2 " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); Thread.Sleep(500); }thread1 啟動后,調用 Join() 方法,直到 thread1 的任務結束,才輪到 thread2 啟動,然后 thread2 也開始任務。實例中,兩個線程就按著嚴格的順序來執行了。如果 thread2 的執行需要依賴于 thread1 中的完整數據的時候,這種方法就可以很好的確保兩個線程的同步性。
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對您有幫助,歡迎給作者打賞