Thread.Join线程阻塞的理解

Thread.Join 方法 ,以C#为例讲解,VB同样适用:

    MSDN:Blocks the calling thread until a thread terminates.

    在Windows中,进行CPU分配是以线程为单位的,一个进程可能由多个线程组成。

演示代码(C#为例):

 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading;
6
7 namespace ConsoleApplication3
8 {
9 class TestThread
10 {
11 static void Main(string[] args)
12 {
13 Thread.CurrentThread.Name = "MainThread";
14 Thread newThread = new Thread(new ThreadStart(ThreadFuncOne));
15 newThread.Name = "NewThread";
16
17 for (int j = 0; j < 100; j++)
18 {
19 if (j == 30)
20 {
21 newThread.Start();
22 newThread.Join(); // 调试时,将该处代码注释掉,比较,会发现join()的作用。
23 }
24 else
25 {
26 Console.WriteLine(Thread.CurrentThread.Name + " j = " + j);
27 }
28 }
29 Console.Read();
30 }
31
32 private static void ThreadFuncOne()
33 {
34 for (int i = 0; i < 100; i++)
35 {
36 Console.WriteLine(Thread.CurrentThread.Name + " i = " + i);
37 }
38 Console.WriteLine(Thread.CurrentThread.Name + " has finished");
39 }
40 }
41 }

 

    具体到代码来说,以上面为例:程序从Main函数开始运行,实际上是有一个线程在执行Main函数,我们称作 MainThread.

    1.首先将 22行代码 newThread.Join();  注释掉,运行。会发现,当程序运行到NewThread.Start() 行以后,主线程和子线程是一起运行的,效果是把各自的数字增大。这说明NewThread,MainThread 是同时运行的。

    2.打开22行代码newThread.Join();运行。会发现,当程序运行到NewThread.Start() 行以后,子线程开始运行,主线程暂停,当子线程结束后,主线程继续。

    基于上面的讨论,我们可以得出结论:

  Blocks the calling thread until a thread terminates.

  the calling thread 就是 MainThread,

  a thread 就是 MainThread调用的NewThread线程。 

    现在回到MSDN的解释,我们可以这么翻译:当 一个新线程(a thread) 调用Join方法的时候,当前线程(Calling Thread) 就被停止执行,直到 新线程(a thread)执行完毕。

     以上为个人理解,如果有 偏差的地方,请各位兄弟指出。

本人博客园:http://www.cnblogs.com/zhuguanhao/

该文章参照:slikyn - 关于C#中Thread.Join()的一点理解
原文地址:http://www.cnblogs.com/slikyn/articles/1525940.html

posted on 2012-03-05 11:47  zhuguanhao  阅读(1480)  评论(0编辑  收藏  举报

导航