On the multi-threaded C # method JOIN

 [Note: When new to multi-threading, could not understand the Join () action, access to three books, are unclear. Later, after some tests of its own, she got to know the Join () nature. We look at whether such an approach I understand, really wrote the Join () the nature, more valuable advice. ]

  Thread class the Join () method can be performed by two threads alternately combined into a thread of execution order. For example, calling the thread A thread B before the Join () method, thread A thread B is inserted, until the thread A is finished, will continue executing thread B.

  Try: threaded insert

  //《C#初学课堂》
    //注意添加命名空间
    using System.Threading;
  
    static void Main(string[] args)
    {
      //线程A
      Thread ThreadA = new Thread(delegate()
      {
        for (int i = 0; i <= 100000000; i++)
        {
          if (i % 1000000 == 0)
          {
            Console.Write('A');
          }
        }
      });
  
      //线程B
      Thread ThreadB = new Thread(delegate()
      {       
        for (int i = 0; i <= 50000000; i++)
        {
          if (i % 1000000 == 0)
          {
            Console.Write('B');
          }
        }
  
        //在这里插入线程A
        ThreadA.Join();
  
        for (int i = 0; i <= 50000000; i++)
        {
          if (i % 1000000 == 0)
          {
            Console.Write('b');
          }
        }
      });
  
      //启动线程
      ThreadA.Start();
      ThreadB.Start();
    }

  Results are as follows, you can analyze it clear why?

[C # beginner class] Multithreading: Thread class Join () method

  As can be seen from the results of operation, a two start threads alternately together when the thread B to execute the statement "ThreadA.Join ()", the thread A is inserted before thread B, the two merged threads, the execution order becomes until all statements in the finished thread a, thread B before going to execute the remaining statements.

  In other words, when we call ThreadA.Join () in the thread B, the method will only return after the thread ThreadA finished. Join () function may also be a parameter indicating the number of acceptable milliseconds after the specified time is reached, if not finished running thread A, then the Join function to return, when thread A and thread B is again in operating state alternately.

Reproduced in: https: //www.cnblogs.com/kevinGao/p/3617420.html

Guess you like

Origin blog.csdn.net/weixin_34122810/article/details/93051986