2016-01-20 257 views
0

我對Thread.Join()方法有一點困惑。我曾見過THIS MSDN帖子和幾個SO帖子,但無法清除這種困惑。關於Thread.Join的困惑

在多線程的情況下,是否等待所有線程完成?或者阻止下一個線程的執行直到第一個完成?假設以下情形:

List<Thread> myThreads = new List<Threads>(); 
while(someCondition == true) 
{ 
    Thread thread = new Thread(new ThreadStart(delegate 
       { 
        processSomeCalculations(x, y); 
       })); 
    thread.Start(); 
    myThreads.Add(thread); 

} 

foreach (Thread thread in myThreads) 
{ 
    thread.Join(); 
} 

Print("all threads completed now"); 

在上述情況下,當thread.Join()被調用列表中的第一項(即列表的第一個線程),does it mean that thread 2 (i.e, the second thread of the list) can NEVER continue its execution, until first thread has been completed?

OR

這是否意味着,all the threads in the list will continue execution in PARALLEL manner, and PRINT method will be called after all threads have finished execution?

我的問題的總結:在上面的場景中,所有的線程都會在PARALLEL中繼續執行嗎?或者他們會在1st執行完後一個一個地執行?

+3

你爲什麼不寫代碼來測試呢? – Enigmativity

回答

3

它是後者,它將阻止主線程上的執行,直到所有已生成的線程都已完成執行,或者在此情況下完成processSomeCalculations(x, y),然後打印"all threads completed now"

2

正如jacob已經說過的,它是後者。 此外,你可以把你的代碼如下所示:

1)啓動多個線程

2)然後,你的循環中:以從列表中的第一個線程和阻塞主線程,直到第一個線程已經完成。只有主線程(即調用.Join()的線程)被阻塞,所有其他線程纔會繼續。

3 ... n)的再次內環:乘坐下一個線程,直到這一次完成阻塞主線程(或只是繼續,如果線程已經完成)

循環後,可以確保所有線程已完成。

+0

所以它意味着,在我的情況下,如果我在循環內部的'thread.start()'後面調用'thread.Join',(而不是像循環中那樣在foreach循環中),它會有相同的影響? – Zeeshan

+0

不,在這種情況下,您將1.啓動第一個線程2.等待,直到第一個線程完成3.啓動第二個線程4.等待,直到第二個線程完成5. ... 調用'myThread。 Join()'被阻塞直到'myThread'完成。 –