• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Kevin Cheng's Yard
电脑是我的老婆,编程是我的灵魂,代码是我的语言,按键是我在歌唱。
https://github.com/surfsky/
博客园    首页    新随笔    联系   管理    订阅  订阅

限制并发线程数例程(C#)

按自己的想法实现的C#版本的限制并发线程数的例程,给有需要的读者

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

namespace WZDM.Test
{
    /// <summary>
    /// 限制并发线程数例程
    /// </summary>
    public class TestThread 
    {
        int _currentThreads = 0;
        int _maxThreads = 10;

        public void Test()
        {
            while (true)
            {
                //_maxThreads = new Random().Next(1, 10);
                for (int i=0; i<100; i++)
                {
                    // 在此进行数量限制
                    if (_currentThreads >= _maxThreads)
                        break;

                    // 开启线程
                    lock (typeof(TestThread))
                    {
                        _currentThreads++;
                        if (_currentThreads > _maxThreads)
                            _currentThreads = _maxThreads;

                        string currentInfo = string.Format("thread {0}/{1}", _currentThreads, _maxThreads);
                        Console.WriteLine(currentInfo + " start");
                        Thread thread = new Thread(new ParameterizedThreadStart(Run));
                        thread.Start(currentInfo);
                    }
                }

                System.Threading.Thread.Sleep(2000);
            }
        }

        // 线程任务
        void Run(object obj)
        {
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine("{0}:{1}", obj, i);
                Thread.Sleep(100);
            }
            Console.WriteLine("{0} finished", obj);


            lock (typeof(TestThread))
            {
                _currentThreads--;
                if (_currentThreads < 0)
                    _currentThreads = 0;
            }
        }
    }
}

转载请注明出处:http://surfsky.cnblogs.com 

posted @ 2008-12-12 09:45  surfsky  阅读(2264)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3