自己弄了个例子为什么我开辟的4个线程运行的时间比 普通的方法时间还长呢?
当然你们会说什么调度 时间片 线程的切换的原因要怎么才快呢?
代码
先新建个类ThreadDemo
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ThreadDemo { public class ThreadDemo { public Thread thread1 = null; public Thread thread2 = null; public Thread thread3 = null; public Thread thread4 = null; public List<int> listInt = null; private List<int> listInt2 = null; private event EventHandler ehRemoveCompleted; public ThreadDemo() { ehRemoveCompleted += new EventHandler(ThreadDemo_ehRemoveCompleted); listInt = new List<int>(); for (int i = 0; i < 10000; i++) { listInt.Add(i); } thread1 = new Thread(Run); thread1.Name = "线程1"; thread2 = new Thread(Run); thread2.Name = "线程2"; thread3 = new Thread(Run); thread3.Name = "线程3"; thread4 = new Thread(Run); thread4.Name = "线程4"; listInt2 = new List<int>(); for (int j = 0; j < 10000; j++) { listInt2.Add(j); } } void ThreadDemo_ehRemoveCompleted(object sender, EventArgs e) { Program.methodWatch.Stop(); Console.WriteLine(Program.methodWatch.ElapsedTicks + "____________________________________"); thread1.Abort(); thread2.Abort(); thread3.Abort(); thread4.Abort(); } public void DoWorker() { thread1.Start(); thread2.Start(); thread3.Start(); thread4.Start(); } void Run() { while (true) { Monitor.Enter(this); if (listInt.Count > 0) { listInt.RemoveAt(0); } Monitor.Exit(this); if (listInt.Count == 0) { ehRemoveCompleted(this, new EventArgs()); } } } public void DoWorker2() { for (int i = 0; i < listInt2.Count; i++) { listInt2.Remove(i); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Diagnostics; namespace ThreadDemo { class Program { public static Stopwatch methodWatch = null; static void Main(string[] args) { ThreadDemo t = new ThreadDemo(); methodWatch = new Stopwatch();//1 methodWatch.Start();//2 t.DoWorker();//3 //先运行上面的 1,2,3 记下结果 然后注释1,2,3 把下面的去掉注释运行 //Stopwatch expWatch = new Stopwatch(); //expWatch.Start(); //t.DoWorker2(); //expWatch.Stop(); //Console.WriteLine(expWatch.ElapsedTicks); } } }
为什么 怎么才能快一点呢?
当然就是调度的原因了(其它可能的性能问题难免有例外,此处忽略)。
调度线程是开支很大的,如果你的线程开支不高的话,走多线程是不合算的。
多线程存在的价值:
1、有需要等待的(比如页面访问、输入等待、输出等待等)。
2、处理周期长,可以通过多线程并行处理的。
你把这个1000改为10000000试试
楼主这种情况,使用多线程效率也不会有提升的,单线程的写法应该是最快了,因为楼主的主线程里没有出现一楼所说的阻塞情况,cpu时间充分利用了