using System; using System.Threading; class IsThreadPool { static Thread regularThread; static void Main() { regularThread = new Thread(new ThreadStart(ThreadMethod)); regularThread.Start(); ThreadPool.QueueUserWorkItem(new WaitCallback(WorkMethod)); Console.ReadLine(); } static void ThreadMethod() { Thread.Sleep(8000); Console.WriteLine("ThreadOne"); } static void WorkMethod(object stateInfo) { //阻止調(diào)用線程(注意:這里是線程池里的后臺線程,而不是regularThread),直到regularThread結(jié)束才繼續(xù)進(jìn)行。 //regularThread.Join(); //阻止調(diào)用線程(這里是線程池里的后臺線程)2秒,直到regularThread結(jié)束或指定時間已過。 //如果該線程在指定的時間內(nèi)完成了,Join將返回True,否則它返回False。 if(regularThread.Join(3000)) Console.WriteLine("true"); else Console.WriteLine("false"); Console.WriteLine("ThreadTwo"); } } 輸出結(jié)果: 3秒后輸出 false ThreadTwo 再過5秒(即總共8秒后)輸出 ThreadOne 如果將ThreadMethod() 的Thread.Sleep(8000);注釋掉 立即輸出結(jié)果: ThreadOne true ThreadTwo |
|