zoukankan      html  css  js  c++  java
  • 限制并发线程数例程(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;
                }
            }
        }
    }

  • 相关阅读:
    【译】在 Chrome 开发者工具中调试 node.js
    2015 年 JavaScript 开发者调查报告
    [译]PostCSS介绍
    [译] Angular 2 VS. React: 血色将至
    使用Fidder将生成环境代码映射到本地(文件夹)
    Sublime Text 3 搭建 React.js 开发环境
    用HTML5+JS开发跨平台的桌面应用
    npm WARN unmet dependency错误解决方法
    【数据结构与算法】线性表操作(C语言)
    【数据结构学习笔记】数组
  • 原文地址:https://www.cnblogs.com/surfsky/p/1353437.html
Copyright © 2011-2022 走看看