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