zoukankan      html  css  js  c++  java
  • 线程平均分配

     public static class TaskUtil
        {
    
            /// <summary>
            /// 多线程执行
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="list"></param>
            /// <param name="action"></param>
            /// <param name="threadNum"></param>
            public static void Do<T>(List<T> list, Action<T> action, int threadNum)
            {
                object o = new object();
                int count = list.Count();
                int avg = count / threadNum;
                int yushu = count % threadNum;
    
                if (avg == 0)
                {
                    ThreadStart ts = () =>
                    {
                        foreach (var item in list)
                        {
                            action(item);
                        }
                    };
                    Thread t = new Thread(ts);
                    t.Start();
                }
                else
                {
                    for (int i = 1; i <= avg; i++)
                    {
                        var tempList = list.Skip((i - 1) * avg).Take(avg).ToList();
                        if (yushu > 0)
                        {
                            tempList.AddRange(list.Skip(i * avg).Take(yushu));
                        }
                        ThreadStart ts = () =>
                        {
                            foreach (var item in tempList)
                            {
                    //在action中注意锁住非堆里面的内容,因为堆是以线程独享,栈是程序共享
                                action(item);
    
                                Console.WriteLine();
    
                            }
                        };
                        Thread t = new Thread(ts);
                        t.Name = "线程" + i;
                        t.Start();
                    }
                }
    
    
                
    
            }
        }
  • 相关阅读:
    my eye
    html与HTML5的区别
    h5css样式
    h5css3弹性盒子
    简单js的介绍
    2020.8.16(周报6)
    2020.8.18
    2020.8.20
    2020.8.17
    2020.8.15
  • 原文地址:https://www.cnblogs.com/lzhp/p/5333314.html
Copyright © 2011-2022 走看看