多線程(五)、同步訪問對象,循環打印1234
阿新 • • 發佈:2018-10-28
thread monit object div lse str == art string
class Program12 { static object obj = new object(); static int lastNum = 4; static void WriteNum(object i) { //lock (obj) //{ //Console.Write(i); //輸出:1234 不加lock是無序的輸出 2134 1324 等 //} //循環寫入10次 1234 for(int k = 0; k < 10; k++) { lock (obj) { if ((int)i == lastNum + 1|| (int)i == lastNum - 3) { if ((int)i==4) { Console.WriteLine(i); }else { Console.Write(i); } lastNum = (int)i; Monitor.PulseAll(obj); } else { k--; Monitor.Wait(obj); } } } }static void Main(string[] args) { Thread t1 = new Thread(WriteNum); Thread t2 = new Thread(WriteNum); Thread t3 = new Thread(WriteNum); Thread t4 = new Thread(WriteNum); t1.Start(1); t2.Start(2); t3.Start(3); t4.Start(4); Console.ReadLine(); } }
多線程(五)、同步訪問對象,循環打印1234