一个关于WaitCallback和ThreadPool.QueueUserWorkItem的小例子

5 篇文章 0 订阅
 
        class CustomThreadPool
        {
            //仅仅只是计数
              public static int count;

            public static Thread QueueUserWorkItem(Action<object> action)
            {
                return QueueUserWorkItem(action, null);
            }

            public static Thread QueueUserWorkItem(Action<object> action, object state)
            {
                Random r = new Random();
                if (r.Next(1, 10) < 4)
                {
                    count++;
                    var th = new Thread(() =>
                    {
                        Console.WriteLine("我在忙,等会处理你的事情");
                        Thread.Sleep(2000);
                        action(state);
                    });
                    th.Start();
                    return th;
                }
                else
                {
                    var th = new Thread(() => action(state));
                    th.Start();
                    return th;
                }
            }
        }

        static void Main(string[] args)
        {
            Thread[] thArr;
            while (true)
            {
                thArr = new Thread[5];
                for (int i = 0; i < 5; i++)
                {
                    if (i % 2 == 0)
                    {
                        thArr[i] = CustomThreadPool.QueueUserWorkItem(s => Console.WriteLine("当前参数是:{0}", s), i.ToString());
                    }
                    else
                    {
                        thArr[i] = CustomThreadPool.QueueUserWorkItem(s => Console.WriteLine("当前参数是:{0}", s));
                    }
                }
                //等待线程执行完毕
                  for (int i = 0; i < 5; i++)
                {
                    thArr[i].Join();
                }

                if (CustomThreadPool.count == 0)
                {
                    Console.WriteLine("RP非常不错");
                }
                CustomThreadPool.count = 0;
                Console.WriteLine("按回车键继续");
                Console.ReadLine();
            }
        }       

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值