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