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