自己弄了個例子為什么我開辟的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 關注
- 384 瀏覽
添加回答
舉報
0/150
提交
取消