线程池控制并发数量

直接限定线程池的最大最小线程数也可以, 但会影响程序其它地方用到线程池的地方,因为线程池的设置是全局的。

这篇文章非常不错, 推荐大家看看:点击打开链接

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

namespace ConsoleApplication15
{

    public class Program
    {
        static void Main(string[] args)
        {
            List<Single> list = new List<Single>();
            list.Add(new Single(1, 1));
            list.Add(new Single(2, 2));
            list.Add(new Single(3, 1));
            list.Add(new Single(4, 2));
            list.Add(new Single(5, 1));
            list.Add(new Single(6, 2));
            list.Add(new Single(7, 2));
            list.Add(new Single(8, 1));
            list.Add(new Single(9, 2));
            list.Add(new Single(10, 1));
            list.ForEach(p => p.ItemList.AddRange(list));

            // 新建 ManualResetEvent 对象并且初始化为无信号状态 
            ManualResetEvent eventX = new ManualResetEvent(false);

            //初始仅加入2个任务
            int maxThreadsCount = 2;
            for (int i = 0; i < maxThreadsCount; i++)
            {
                Single item = list[i];
                item.EventX = eventX;
                ThreadPool.QueueUserWorkItem(new WaitCallback(item.Exec), null);
            }

            //等待事件的完成,即线程调用 ManualResetEvent.Set() 方法 
            eventX.WaitOne(Timeout.Infinite, true);

            for (int i = 0; i < maxThreadsCount; i++)
            {
                Single item = list[i];
                item.PrintFlag();
                Console.WriteLine();
            }
            Console.ReadKey();
        }
    }//end of class Program

    public class Single
    {
        #region [属性]
        public int Flag { get; set; }
        public int NextFlag { get; set; }
        public DateTime BeginTime { get; set; }
        public DateTime EndTime { get; set; }
        public int WaitMs { get; set; }
        public bool Pending { get; set; }
        public bool Finished { get; set; }
        public List<Single> ItemList { get; set; }
        public ManualResetEvent EventX { get; set; }

        public double ElaspedSeconds
        {
            get
            {
                return this.EndTime.Subtract(this.BeginTime).TotalSeconds;
            }
        }
        #endregion

        public Single(int _flag, int _waitSeconds)
        {
            this.Flag = _flag;
            this.WaitMs = _waitSeconds * 1000;
            this.Pending = false;
            this.Finished = false;
            this.ItemList = new List<Single>();
        }

        public void Exec(object obj)
        {
            this.Pending = true;
            this.BeginTime = DateTime.Now;
            Thread.Sleep(this.WaitMs);
            this.EndTime = DateTime.Now;
            this.Finished = true;

            lock (this.ItemList)
            {
                Console.WriteLine("Flag:{0}, BeginTime:{1:HH:mm:ss,ms}, EndTime: {2:HH:mm:ss,ms}, ElapsedSeconds:{3}"
                    , this.Flag < 10 ? " " + this.Flag.ToString() : this.Flag.ToString()
                    , this.BeginTime
                    , this.EndTime
                    , this.ElaspedSeconds
                    );
                Single item = ItemList.Find(p => !p.Pending);
                //如果全部都运行过了
                if (item == null) 
                {
                    //如果全部都运行完了
                    if (ItemList.Find(p => !p.Finished) == null) 
                    {
                        //注:此处设置状态为终止
                        this.EventX.Set();
                    }
                    return;
                }

                this.NextFlag = item.Flag;
                //注意此处要赋值,否则会null异常
                item.EventX = this.EventX;
                ThreadPool.QueueUserWorkItem(new WaitCallback(item.Exec), null);
            }
        }

        public void PrintFlag()
        {
            if (this.NextFlag == 0)
            {
                Console.WriteLine("{0}, WaitSeconds:{2}", this.Flag, this.NextFlag, this.WaitMs / 1000);
                return;
            }

            Console.WriteLine("{0}->{1}, WaitSeconds:{2}", this.Flag, this.NextFlag, this.WaitMs/1000);
            Single next = this.ItemList.Find(p => p.Flag == this.NextFlag);
            if (next != null)
            {
                next.PrintFlag();
            }
        }
    }//end of class Single
}//end of namespace


分配得很好,赞!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用线程池控制并发请求可以通过ThreadPoolExecutor来实现。ThreadPoolExecutor是Java中线程池的核心实现类。通过创建一个ThreadPoolExecutor对象,我们可以配置线程池的各种参数来控制任务的执行。 首先,需要确定核心线程池的大小(corePoolSize),即同时执行任务的最大线程数。通过构造函数中的corePoolSize参数,我们可以设置线程池的核心线程大小。 接下来,我们需要设置线程池的最大线程数(maximumPoolSize),即线程池中允许存在的最大线程数。当任务数量超过核心线程池大小时,线程池会自动创建新的线程来执行任务,直到达到最大线程数为止。 除了核心线程池大小和最大线程数,我们还可以设置线程的存活时间(keepAliveTime)。当线程池中的线程数量大于核心线程池大小,并且空闲时间超过了keepAliveTime时,多余的线程会被销毁,以节省资源。 另外,在ThreadPoolExecutor中,还可以设置任务队列(runnableTaskQueue)来存储待执行的任务。任务队列可以是有界队列,也可以是无界队列。当线程池中的线程数量达到核心线程池大小时,多余的任务会被存储在任务队列中,等待执行。 最后,我们还可以设置线程工厂(threadFactory)和异常处理器(handler)。线程工厂用于创建线程,异常处理器用于处理任务执行过程中发生的异常。 通过合理配置ThreadPoolExecutor的参数,我们可以灵活控制并发请求的执行,提高系统的并发性能。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [JAVA线程池详解(ThreadPoolExecutor)](https://blog.csdn.net/ChengHuanHuaning/article/details/125380179)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值