zoukankan      html  css  js  c++  java
  • C# Thread.Join()

    Thread.Join() 官网解释如下:

    https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.thread.join?view=netframework-4.8

    在此实例表示的线程终止前,阻止调用线程。

    如下代码,thread1 是最先运行,但是由于执行 thread2.join() 阻塞了线程,所以必须等到 thread2 线程执行完成后,才会继续执行 thread1。

    也就是:前线程CurThread将被阻塞,直到CalleeThread线程完成后CurThread 刚刚CalleeThread.Join() 的后续代码才继续往下执行

    using System;
    using System.Threading;
    
    public class Example
    {
       static Thread thread1, thread2;
       
       public static void Main()
       {
          thread1 = new Thread(ThreadProc);
          thread1.Name = "Thread1";
          thread1.Start();
          
          thread2 = new Thread(ThreadProc);
          thread2.Name = "Thread2";
          thread2.Start();   
       }
    
       private static void ThreadProc()
       {
          Console.WriteLine("
    Current thread: {0}", Thread.CurrentThread.Name);
          if (Thread.CurrentThread.Name == "Thread1" && 
              thread2.ThreadState != ThreadState.Unstarted)
             thread2.Join();
          
          Thread.Sleep(4000);
          Console.WriteLine("
    Current thread: {0}", Thread.CurrentThread.Name);
          Console.WriteLine("Thread1: {0}", thread1.ThreadState);
          Console.WriteLine("Thread2: {0}
    ", thread2.ThreadState);
       }
    }
    // The example displays output like the following:
    //       Current thread: Thread1
    //       
    //       Current thread: Thread2
    //       
    //       Current thread: Thread2
    //       Thread1: WaitSleepJoin
    //       Thread2: Running
    //       
    //       
    //       Current thread: Thread1
    //       Thread1: Running
    //       Thread2: Stopped

    有一篇解释的还可以的文章:

    https://www.cnblogs.com/slikyn/articles/1525940.html

  • 相关阅读:
    uva-321-暴力枚举-隐式图搜索
    uva-704-暴力枚举-双向bfs
    整数的无符号编码和有符号编码
    HDU 5793
    HDU 5730
    HDU 5740
    HDU 5768
    HDU 1194
    HDU 1086
    HDU 5145
  • 原文地址:https://www.cnblogs.com/ryanzheng/p/10962468.html
Copyright © 2011-2022 走看看