測試多線程示例:用計數器控制ThreadPool線程數量

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ThreadPool_Threading
{
    class Program
    {
        static int execNum = 0;
        static void Main()
        {
            int i = 0;
            while (true)
            {
                i += 1;
                while (execNum >= 500)
                {
                    Thread.Sleep(10);
                   // Console.WriteLine("sleep");
                }
                Interlocked.Increment(ref execNum);
                ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), i);
            }

        }
        private static void ThreadProc(object i)
        {
            Console.WriteLine(i.ToString());
            Interlocked.Decrement(ref execNum);
            //Console.WriteLine("execNum:" + execNum);

        }


    }
}
 

 

不一定正確,mark

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章