实例为多线程分配代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
ThreadNum =(int) numericUpDown1.Value;//线程数 _thread = new Thread[ThreadNum];//初始化线程数组 int VideoNum = li.Count;//视频总数量 int singelNum = VideoNum / ThreadNum;//平均分配 int remainder = VideoNum % ThreadNum;//获取剩余 for (int i = 0; i < ThreadNum; i++) { List<int> range = new List<int>(); range.Add(i * singelNum); if (remainder != 0 && (ThreadNum - 1) == i) //剩余的交给最后一个线程 { range.Add(i * singelNum + singelNum + remainder - 1); } else { range.Add(i * singelNum + singelNum - 1); } //下载指定位置的数据 int[] ran = new int[] { range[0], range[1] }; _thread[i] = new Thread(new ParameterizedThreadStart(GetMoreVideoUrl)); _thread[i].Start(ran); } private void GetMoreVideoUrl(object obj) { int[] ran = obj as int[]; for(int i=ran[0];i<=ran[1];i++) { if (tag == 1) { myResetEvent.WaitOne(); } GetVideoUrl(li[i]); } lock (locker)completeNum++; } |
用ParameterizedThreadStart创建一个带参数的线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Threading; public class Work { public static void Main() { Thread newThread = new Thread( new ParameterizedThreadStart(doWork) ); newThread.start("456"); public static void doWork(object ob) { Console.WriteLine("123" + ob.ToString()); } } } |
[v_tips]输出123456[/v_tips]
正常情况下创建线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Threading; public class Work { public static void Main() { Thread newThread = new Thread(Work.DoWork); newThread.start(); public static void DoWork(object data) { Console.WriteLine("123"); } } } |
此文为(卤卤虾)原创内容,特此声明
近期评论