C#多线程使用锁解决争抢资源问题

C#多线程使用锁解决争抢资源问题

class Program
    {
        static object locker=new Object();
        static int init = 100;
        static void Main(string[] args)
        {
            for (int i = 1; i <= 5; i++)
            {
                ThreadStart ts = new ThreadStart(run);
                Thread th = new Thread(ts);
                th.Start();
            }
            Console.ReadLine();
        }
        static void run()
        {
            lock (locker) { 
                while (init > 0) {
                    init--;
                    Console.WriteLine("线程:"+Thread.CurrentThread.Name+",执行减1后的结果:"+init.ToString());
                    //Thread.Sleep(100);
                }
            }
        }
    }
发布了48 篇原创文章 · 获赞 3 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/chscomfaner/article/details/103729815