Amoon哥早就和我说过:使用多线程时线程间的切换会浪费掉比单线程更多的时间,无奈一直是用VB6的,写不了多线程的东西[当然,如果非要玩P-Code的话也行!但是,那样的话…………]
现在出来了.NET,刚看了2天,发现在DotNet里做多线程很简单哦!!正好来检验一下:
用C#写的,因为刚刚接触C#,时间太短了!!所以,实现的方法很笨拙!如果有前辈看到的话还望不惜指点一二。
实现如下:
设计视图:
新建一个Windows应用程序,在Form1上添加button1和button2!
代码Form1.cs中:
引入线程名称空间:
using System.Threading;
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void button1_Click(object sender, System.EventArgs e)
{
T1 t1 = new T1();
T2 t2 = new T2();
Console.WriteLine("ST Method-------------{0}:{1}", DateTime.Now.Second.ToString(), DateTime.Now.Millisecond.ToString());
t1.RunTest();
t2.RunTest();
}
private void button2_Click(object sender, System.EventArgs e)
{
T1 t1 = new T1();
T2 t2 = new T2();
Thread thd1 = new Thread(new ThreadStart(t1.RunTest));
Thread thd2 = new Thread(new ThreadStart(t2.RunTest));
Console.WriteLine("MT Method-------------{0}:{1}", DateTime.Now.Second.ToString(), DateTime.Now.Millisecond.ToString());
thd1.Start();
thd2.Start();
}
public class T1
{
public void RunTest()
{
for(int i = 0; i < 500; i++)
Console.WriteLine("Thread1:{0}", i);
Console.WriteLine("-------------{0}:{1}", DateTime.Now.Second.ToString(), DateTime.Now.Millisecond.ToString());
}
}
public class T2
{
public void RunTest()
{
for(int i = 0; i < 500; i++)
Console.WriteLine("Thread2:{0}", i);
Console.WriteLine("-------------{0}:{1}", DateTime.Now.Second.ToString(), DateTime.Now.Millisecond.ToString());
}
}
最后得到的结果:
第一次比较:
ST Method-------------3:656
-------------5:921
间隔:2.265
MT Method-------------40:656
-------------43:109
间隔:2.453
第二次比较:
ST Method-------------29:859
-------------32:109
间隔:2.25
MT Method-------------0:843
-------------3:125
间隔:2.282
不比了,每次都是单线程的快!!!
由此,接下来要考虑的就是何时用多线程编写程序呢???