C#執行緒範例:Sleep()方法


在執行的執行緒上呼叫Sleep()方法來指定的毫秒暫停當前執行緒。從面使其他執行緒有機會開始執行。

using System;
using System.Threading;
public class MyThread
{
    public void Thread1()
    {
        for (int i = 0; i < 10; i++)
        {
            String curTime = DateTime.Now.ToString();
            Console.WriteLine("Thread1 at "+ curTime + " => "+ i);
            Thread.Sleep(500);// 掛起半秒
        }
    }
}
public class ThreadExample
{
    public static void Main()
    {
        MyThread mt = new MyThread();
        Thread t1 = new Thread(new ThreadStart(mt.Thread1));
        Thread t2 = new Thread(new ThreadStart(mt.Thread1));
        t1.Start();
        t2.Start();
    }
}

執行上面範例程式碼,得到以下結果 -

Thread1 at 2017/9/13 3:24:42 => 0
Thread1 at 2017/9/13 3:24:42 => 0
Thread1 at 2017/9/13 3:24:42 => 1
Thread1 at 2017/9/13 3:24:42 => 1
Thread1 at 2017/9/13 3:24:43 => 2
Thread1 at 2017/9/13 3:24:43 => 2
Thread1 at 2017/9/13 3:24:43 => 3
Thread1 at 2017/9/13 3:24:43 => 3
Thread1 at 2017/9/13 3:24:44 => 4
Thread1 at 2017/9/13 3:24:44 => 4
Thread1 at 2017/9/13 3:24:44 => 5
Thread1 at 2017/9/13 3:24:44 => 5
Thread1 at 2017/9/13 3:24:45 => 6
Thread1 at 2017/9/13 3:24:45 => 6
Thread1 at 2017/9/13 3:24:45 => 7
Thread1 at 2017/9/13 3:24:45 => 7
Thread1 at 2017/9/13 3:24:46 => 8
Thread1 at 2017/9/13 3:24:46 => 8
Thread1 at 2017/9/13 3:24:46 => 9
Thread1 at 2017/9/13 3:24:46 => 9