在执行的线程上调用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