C#線程實例:Join()方法

Join()方法使所有的調用線程等待直到當前線程(已連接線程)終止或完成其任務。

參考以下示例 -

using System;
using System.Threading;
public class MyThread
{
    public void Thread1()
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Thread1 : "+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));
        Thread t3 = new Thread(new ThreadStart(mt.Thread1));
        t1.Start();
        t1.Join();
        t2.Start();
        t3.Start();
    }
}

執行上面示例代碼,得到以下結果 -

Thread1 : 0
Thread1 : 1
Thread1 : 2
Thread1 : 3
Thread1 : 4
Thread1 : 0
Thread1 : 0
Thread1 : 1
Thread1 : 1
Thread1 : 2
Thread1 : 2
Thread1 : 3
Thread1 : 3
Thread1 : 4
Thread1 : 4