关于线程的一个练习

下面是一个我们学习线程的一个小例子,大家看看。

实现两个线程,A为控制线程,B为工作线程,要求:
1、从A中读入一个整数;
2、根据A中读入的数字计算其阶乘,同时将结果输入到D盘根目录下的1.txt文件中。该结果需要重复写入1000次,但当用户输入的整数发生改变时,中断写入,并计算新数字的阶乘,将结果追加到1.txt中;
3、输入0退出。

程序如下:

using System;
using System.IO;
using System.Threading;

namespace ThreadTest
{
 /// <summary>
 /// Class1 的摘要说明。
 /// </summary>
 class Test
 {
  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  ///
  public static TextWriter writer;
  public static Thread A;
  public static Thread B;
  public static int readData;

  public static void ThreadA()
  {
   while (true)
   {
    Console.WriteLine("请输入整数:");
    string s=Console.ReadLine();

    if (s==""||s=="0")
    {
     writer.Close();
     break;
    }
    else
    {
     if (s!=readData.ToString())
     {
      readData=Convert.ToInt32(s);
      if (B!=null)
      {
       B.Abort();
      }
      B=new Thread(new ThreadStart(ThreadB));
      B.Start();
     }
    }

   }
  }

  public static void ThreadB()
  {
   //重复1000次;
   for (int i=0;i<1000;i++)
   {
    long result=1;

    //计算阶乘;
    for (long j=1;j<=(long)readData;j++)
    {
     result*=j;
    }
    if (writer==null)
    {     
     writer=File.AppendText(@"D:\1.txt");     
    }
    writer.WriteLine("{0}",result);
    writer.Flush();
   }   
  }
 
  [STAThread]
  static void Main(string[] args)
  {  

   A=new Thread(new ThreadStart(ThreadA));
   A.Start();
  }
 }
}

原文地址:https://www.cnblogs.com/wayfarer/p/4525.html