2016-01-20 259 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'完成。 –