关于Thread.IsAlive属性
今天在讨论多线程的时候,谈到了这个属性。IsAlive,顾名思义,它表示线程当前是否为可用状态,如果线程已经启动,并且当前没有任何异常的话,则返回true,否则为false
为什么要了解这个属性,是因为下面代码有的朋友不是很理解
下面代码演示的多个线程对共享资源争用的问题,具体细节这里不详细讨论了。
Thread thread1 = new Thread(new ThreadStart(SomeMethod)); Thread thread2 = new Thread(new ThreadStart(SomeMethod)); Thread thread3 = new Thread(new ThreadStart(SomeMethod)); Thread thread4 = new Thread(new ThreadStart(SomeMethod)); Thread thread5 = new Thread(new ThreadStart(SomeMethod)); thread1.Name = "Thread 1"; thread2.Name = "Thread 2"; thread3.Name = "Thread 3"; thread4.Name = "Thread 4"; thread5.Name = "Thread 5"; thread1.Start(); while (!thread1.IsAlive) Thread.Sleep(100); thread2.Start(); while (!thread2.IsAlive) Thread.Sleep(100); thread3.Start(); while (!thread3.IsAlive) Thread.Sleep(100); thread4.Start(); while (!thread4.IsAlive) Thread.Sleep(100); thread5.Start(); while (!thread5.IsAlive) Thread.Sleep(100);
大家有些疑惑的是,为什么Thread.Start之后,要用while去等待它Alive呢?这个代码通常不写的话,也是没有什么问题的。
但原理上说,其实简单地Start,并不代表线程能马上启动起来(也许CPU正在忙其他的事情),当然它迟早会被启动起来,但上面的代码确保了几个线程是依次被启动的。