其实多线程最复杂的地方在于不同线程间的同步问题,这其中会涉及到先后执行问题、共享变量问题等。这篇文章我们主要来开个头,看一下join方法。
- 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");
- }
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");
}
- static void PrintNumbersWithDelay()
- {
- Console.WriteLine("Starting...");
- for (int i = 1; i < 10; i++)
- {
- Thread.Sleep(2000);
- Console.WriteLine(i);
- }
- }
- }
- }
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线程的先后逻辑关系。