国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#線程的一個練習例子

2023-05-20 20:23:40
字體:
來源:轉載
供稿:網友

實現兩個線程,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();
}
}
}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 铜山县| 肇州县| 黄浦区| 衡阳市| 怀集县| 湟中县| 四平市| 包头市| 新竹县| 五常市| 弥勒县| 来凤县| 夏邑县| 衡阳市| 岚皋县| 土默特左旗| 鞍山市| 莱阳市| 株洲市| 大渡口区| 呼伦贝尔市| 东至县| 永福县| 大悟县| 潢川县| 南丰县| 永修县| 南通市| 东辽县| 循化| 湘西| 阿巴嘎旗| 沁水县| 张家界市| 应城市| 沙田区| 凤山市| 宜川县| 田阳县| 吕梁市| 华宁县|