zoukankan      html  css  js  c++  java
  • Thread.Join()方法的理解

          今天是第一次在C#中接触Thread,自己研究了一下其中Thread.Join()这个方法,下面谈谈自己的理解。

          Thread.Join()在MSDN中的解释很模糊:Blocks the calling thread until a thread terminates

    有两个主要问题:1.什么是the calling thread?

                           2.什么是a thread?

           首先来看一下有关的概念: 我们执行一个.exe文件实际上就是开启了一个进程,同时开启了至少一个线程,

    但是真正干活的是线程,就好比一个Team有好几个人,但是真正干活的是人不是Team.

          具体到代码来说,以Console Application为例:程序Test.exe从Main函数开始运行,实际上是有一个线程

    在执行Main函数,我们称作MainThread.假如我们在Main函数中声明了一个Thread,称作NewThread,并且调用了

    NewThread.Start()的方法,那么 MainThread在处理Main函数里面的代码时遇到NewThread.Start()时,就会

    去调用NewThread.

           基于上面的讨论,我们可以得出结论:在我们刚才的例子中the calling thread就是MainThread,而a thread

    指的洽洽就是MainThread调用的NewThread线程。

           现在回到MSDN的解释,我们可以这么翻译:当NewThread调用Join方法的时候,MainThread就被停止执行,

    直到NewThread线程执行完毕 这样就好理解了吧O(∩_∩)O哈哈~

           好了,前面分析完了,现在来看测试用例吧:

    Titleusing 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();
            }
        }
    }
  • 相关阅读:
    查看客户端的IP地址,机器名,MAC地址,登陆名等信息
    查看sqlserver 2008中性能低下的语句
    搜索包含指定关键字的存储过程
    获得客户端详细信息以及每个进程的sql语句
    实战:sqlserver 日常检查脚本
    NIO的学习总结
    JavaWEB过滤器和监听器技术
    抽象工厂模式代码:
    详解 equals() 方法和 hashCode() 方法
    net.sf.json JSONObject与JSONArray使用实例
  • 原文地址:https://www.cnblogs.com/cpcpc/p/2123136.html
Copyright © 2011-2022 走看看