Thread.Join() 方法


MSDN:Blocks the calling thread until a thread terminates

1. 什么是 the calling thread?

2. 什么是 a thread?

 

運行一個程序,即開啟了一個進程和至少一個線程,干活的是線程而非進程!the calling thread 我們可以認為是MainThread(或者調用線程的線程,是不是有點繞?呵呵),a thread 我們就認為是被調用的線程。

 

最后,我們可以這樣翻譯MSDN:當 a thread 調用Join方法的時候,MainThread 就被停止執行,直到 a thread 線程執行完畢。

 

下面是測試代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
 
namespace Test
{
    class TestThread
    {
        private static void ThreadFuncOne()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(Thread.CurrentThread.Name +"   i =  " + i);
            }
            Console.WriteLine(Thread.CurrentThread.Name + " has finished");
        }
 
        static void Main(string[] args)
        {
            Thread.CurrentThread.Name = "MainThread";
 
            Thread newThread = new Thread(new ThreadStart(TestThread.ThreadFuncOne));
            newThread.Name = "NewThread";
 
            for (int j = 0; j < 20; j++)
            {
                if (j == 10)
                {
                    newThread.Start();
                    newThread.Join();
                }
                else
                {
                    Console.WriteLine(Thread.CurrentThread.Name + "   j =  " + j);
                }
            }
            Console.Read();
        }
    }
}

 

image

 

結論:

MainThread 在 NewThread.Join() 被調用后被阻塞,直到 NewThread 執行完畢才繼續執行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM