线程的等待方法:join

其实多线程最复杂的地方在于不同线程间的同步问题,这其中会涉及到先后执行问题、共享变量问题等。这篇文章我们主要来开个头,看一下join方法。

  1. using System;  
  2. using System.Threading;  
  3.   
  4. namespace Chapter1.Recipe3  
  5. {  
  6. class Program  
  7. {  
  8. static void Main(string[] args)  
  9. {  
  10. Console.WriteLine("Starting program...");  
  11. Thread t = new Thread(PrintNumbersWithDelay);  
  12. t.Start();  
  13. t.Join(); // 等待t线程完成后,主线程才继续执行!  
  14. Console.WriteLine("Thread completed");  
  15. }  
using System;
using System.Threading;

namespace Chapter1.Recipe3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting program...");
Thread t = new Thread(PrintNumbersWithDelay);
t.Start();
t.Join(); // 等待t线程完成后,主线程才继续执行!
Console.WriteLine("Thread completed");
}

  1. static void PrintNumbersWithDelay()  
  2. {  
  3. Console.WriteLine("Starting...");  
  4. for (int i = 1; i < 10; i++)  
  5. {  
  6. Thread.Sleep(2000);  
  7. Console.WriteLine(i);  
  8. }  
  9. }  
  10. }  
  11. }  
static void PrintNumbersWithDelay()
{
Console.WriteLine("Starting...");
for (int i = 1; i < 10; i++)
{
Thread.Sleep(2000);
Console.WriteLine(i);
}
}
}
}

其实join方法的意义很简单,主线程main在t没有执行完毕前都会保持阻塞状态(类似于sleep状态),这样做的好处是保证了线程t在join前一定会执行完毕,确保了main和t线程的先后逻辑关系。

猜你喜欢

转载自www.cnblogs.com/cuihongyu3503319/p/9232298.html