實現兩個線程,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();
}
}
}
|
新聞熱點
疑難解答
圖片精選