线程平均分配
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();}}
}}
?
總結
- 上一篇: 有氧运动 无氧运动
- 下一篇: Hessian入门(与Spring集成)