線程操作之線程休眠
時間:2020-08-13 作者:管理員(yuán) 點擊:726
線程的休眠是通過Thread類的Sleep方法實現的(休眠的時間是以毫秒爲單位的),而Thread類的實例的IsAlive屬性可以判斷線程是否執行完畢,Sleep方法的使用格式爲:
實例代碼如下(xià):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace 線程休眠
{
class Program
{
static void Main(string[] args)
{
ThreadStart ts = new ThreadStart(method);
Thread t = new Thread(ts);
t.Start();
while (t.IsAlive)
{
Console.WriteLine("線程開(kāi)始執行!");
Thread.Sleep(1);//設置休眠時間爲1毫秒
}
Console.ReadKey();
}
public static void method()
{
string state;
for (int i = 1; i < 5001; i++)
{
state = Thread.CurrentThread.ThreadState.ToString();
if (i % 5 == 0)
{
Console.WriteLine("當前線程狀态爲:{0}", state);
}
}
}
}
}