Thread.Join 的用法)加個人理解

來源:互聯網
上載者:User

Thread.Join()用法的理解
 // Blocks the calling thread until a thread terminates
  指在一線程裡面調用另一線程join方法時,表示將本線程阻塞直至另一線程終止時再執行  
  比如  

     class Program
    {
        static void Main()
        {
            System.Threading.Thread x = new System.Threading.Thread(new System.Threading.ThreadStart(f1));
            x.Start();
            Console.WriteLine("This is Main.{0}", 1); // 第一
            x.Join(); // 主線程等待x結束
            Console.WriteLine("This is Main.{0}", 2); // 第四
            Console.ReadLine();
        }
        static void f1()
        {
            System.Threading.Thread y = new System.Threading.Thread(new System.Threading.ThreadStart(f2));
            y.Start();
            y.Join(); // x線程等待y線程結束, 第二
            Console.WriteLine("This is F1.{0}", 1);
        }

        static void f2()
        {
            Console.WriteLine("This is F2.{0}", 1); // y線程執行,第三
        }
     }

這兒有三個線程在處理(包括主線程),大家可看看執行結果.
結果:
This is Main.1
This is F2.1
This is F1.1
This is Main.2

如果: 注釋//  x.Join();
結果:
This is Main.1
This is Main.2
This is F2.1
This is F1.1

另外:大家可以看看以下幾個方法的區別,有興趣的朋友可以用上面的例子進行測試

Thread.Suspend():掛起線程,或者如果線程已掛起,則不起作用;
Thread.Resume():繼續已掛起的線程;
Thread.Interrupt():中止處於 Wait或者Sleep或者Join 線程狀態的線程;
Thread.Sleep():將當前線程阻塞指定的毫秒數;
name:平平
mail:xzp91032@163.com

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.