动态开启多个线程

参考  

一、利用Task动态创建多个线程进行任务处理

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Script.Serialization;

namespace ConsoleApp7
{

    class Program
    {
        /// <summary>
        /// 最多允许创建的线程数,可以通过配置文件来配置
        /// 具体的值也该是由:服务器资源+接口限制等多因数来确定的
        /// </summary>
        public static int maxThread = 10;
        static void Main(string[] args)
        {
            // 假设选择处理20条酒店数据
            List<string> listHotel = new List<string>();
            for (int i = 0; i < 20; i++)
            {
                listHotel.Add($"我是酒店{(i + 1).ToString().PadLeft(2, '0')}");
            }

            // 创建Tsak处理酒店数据同步
            AsyncDynamicSynchronouslyHotel(listHotel);
            Console.ReadLine();
        }
        /// <summary>
        /// 根据酒店数据量,动态创建Tsak来处理酒店数据同步
        /// </summary>
        /// <param name="listHotel">待处理的酒店数据列表</param>
        private static void AsyncDynamicSynchronouslyHotel(List<string> listHotel)
        {
            object hotelTaskLock = new object();

            // 先做一个非空判断
            if (listHotel == null || listHotel.Count < 1)
            {
                return;
            }

            // task线程数组
            List<Task> taskList = new List<Task>();

            // 首先根据资源数据量+最大允许线程数来确定需要开启的线程
            int taskCount = listHotel.Count < maxThread ? listHotel.Count : maxThread;

            // 创建指定是task线程数
            for (int i = 0; i < taskCount; i++)
            {
                // 创建一个task线程
                taskList.Add(new Task(() =>
                {
                    while (listHotel != null && listHotel.Count > 0)
                    {
                        // 给该线程分配一个酒店处理任务
                        string hotelInfro = string.Empty;

                        // 线程通过,加一个资源锁
                        lock (hotelTaskLock)
                        {
                            // 在获取到锁后,还需要做一个资源判断,避免获取到锁后,资源以及被消耗完毕
                            if (listHotel != null && listHotel.Count > 0)
                            {
                                hotelInfro = listHotel[0];
                                listHotel.Remove(hotelInfro);
                            }
                        }

                        // 开始模拟真正的数据同步操作(在这个里面写具体的业务)
                        if (!string.IsNullOrEmpty(hotelInfro))
                        {
                            Console.WriteLine($"我是线程ID{Thread.CurrentThread.ManagedThreadId.ToString()  },开始酒店【{hotelInfro}的数据同步处理");
                            Thread.Sleep(100000);
                            Console.WriteLine($"我是线程ID{Thread.CurrentThread.ManagedThreadId.ToString()  },完成酒店【{hotelInfro}的数据同步处理");
                        }
                    }
                }));

                // 启动线程
                taskList[i].Start();
            }
        }
    }
}

 二、利用Thread

有时候,主线程需要等待子线程执行完后在执行,Thread的线程等待我们使用join()来实现

static void Main(string[] args)
        {
            Console.WriteLine("----------主程序开始,线程ID是{0}-----------------", Thread.CurrentThread.ManagedThreadId);

            List<Thread> list = new List<Thread>();
            for(int i = 0;i< 5;i++)
            {
                ParameterizedThreadStart method = o => TestThread(o.ToString());
                Thread thread = new Thread(method);
                thread.Start("param" + i);
                list.Add(thread);
            }
            foreach (var t in list)
            {
                t.Join();
            }
            Console.WriteLine("----------主程序结束,线程ID是{0}-----------------", Thread.CurrentThread.ManagedThreadId);

            Console.Read();
        }

        static void TestThread(string name)
        {
            Console.WriteLine("TestThread Start name:{0} 当前线程id:{1} 当前时间:{2}", name, Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString());

            long sum = 0;

            for (int i = 0; i < 10000000; i++)
            {
                sum += i;
            }
            Console.WriteLine("TestThread End name:{0} 当前线程id:{1} 当前时间:{2}", name, Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString());
        }
原文地址:https://www.cnblogs.com/macT/p/11881060.html