zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Maven MicroTip: Get sources and Javadocs
    重定向标准流
    Unix: How to redirect stderr to stdout
    ruby doc
    1. 数据流重定向(stdin,stdout,stderr)
    jruby.org十多M的jar都是放到amazon s3上提供服务的
    试试rvm
    ruby doc
    Velocity用户手册中文版
    对Windows Mobile Timer不准的总结
  • 原文地址:https://www.cnblogs.com/zhuguanhao/p/2380234.html
Copyright © 2011-2022 走看看