自己弄了个例子为什么我开辟的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 listInt = null;
private List listInt2 = null;
private event EventHandler ehRemoveCompleted;
public ThreadDemo()
{
ehRemoveCompleted += new EventHandler(ThreadDemo_ehRemoveCompleted);
listInt = new List();
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();
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);
}
}
}
为什么 怎么才能快一点呢?
- 3 回答
- 0 关注
- 357 浏览
添加回答
举报
0/150
提交
取消