多线程比单线程到底慢了多少!!!

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


不比了,每次都是单线程的快!!!
由此,接下来要考虑的就是何时用多线程编写程序呢???

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值