重新学C#编程159-Threadstart创建线程2

前面的练习时显示1-10的偶数,这是一个单线程,接下来实验一下双线程,在前一个练习基础上把数据范围扩大一下。

新建一个控制台项目,用两个线程分别显示偶数和奇数。

完整代码如下

using System;
using System.Threading;
namespace ThreadStart练习2
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("ThreadStart练习");
      ThreadStart threadStart1 = new ThreadStart(showEven);
      Thread thread1 = new Thread(threadStart1);
      ThreadStart threadStart2 = new ThreadStart(showOdd);
      Thread thread2 = new Thread(threadStart2);
      thread1.Start();
      thread2.Start();
    }
    public static void showEven()//显示偶数
    {
      for(int i=2;i<=100;i+=2)
      {
        Console.Write(i + " ");
      }
    }
    public static void showOdd()//显示奇数
    {
      for(int i=1;i<=100;i+=2)
      {
        Console.Write(i + " ");
      }
    }
  }
}

 运行结果为

可以看出,显示偶数和显示奇数是两个线程,程序里面先后调用,但是并不胡等第一个线程完全结束再执行第二个线程。每次执行结果都不一样。

posted @ 2021-07-05 08:32  来自金沙江的小鱼  阅读(42)  评论(0编辑  收藏  举报