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();
                    }
                }
    
    
                
    
            }
        }
  • 相关阅读:
    卡特兰数
    hdu 1023 Train Problem II
    hdu 1022 Train Problem
    hdu 1021 Fibonacci Again 找规律
    java大数模板
    gcd
    object dection资源
    Rich feature hierarchies for accurate object detection and semantic segmentation(RCNN)
    softmax sigmoid
    凸优化
  • 原文地址:https://www.cnblogs.com/lzhp/p/5333314.html
Copyright © 2011-2022 走看看