多线程同步访问对象,循环打印1234
Posted 25miao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程同步访问对象,循环打印1234相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章