c# 线程池+原子锁+完成提示

 class Program
    {


        const int cycleNum = 200;
        static int cnt = 200;
        static AutoResetEvent myEvent = new AutoResetEvent(false);
        static void Main(string[] args)
        {
            ThreadPool.SetMinThreads(10, 20);
            ThreadPool.SetMaxThreads(10, 20);
            for (int i = 1; i <= cycleNum; i++)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(testFun), i.ToString());
            }
            Console.WriteLine("主线程执行!");
            Console.WriteLine("主线程结束!");
            myEvent.WaitOne();
            Console.WriteLine("线程池终止!");
            Console.ReadKey();
        }
        public static void testFun(object obj)
        {
            //cnt -= 1;
            int c=Interlocked.Decrement(ref cnt);

            Console.WriteLine(string.Format("{0}:第{1}个线程", DateTime.Now.ToString(), obj.ToString())+c.ToString());
            Thread.Sleep(2000);
            if (cnt == 0)
            {
                myEvent.Set();
            }
        }

 

posted @ 2020-07-13 05:44  肥宅123  阅读(515)  评论(0)    收藏  举报