了解线程Join()方法

时间:2022-08-07 05:20:17

Join的官方解释: 阻塞调用线程,直到某个线程终止或经过了指定时间为止
Q:谁是调用线程?

A:Join代码写在那,哪个就是调用线程,在本例中主线程是调用线程
Q:某个线程又是指的是谁?
A:如本例thread1执行了Join方法,thread1为某个线程

 

using System; 
using System.Threading; 
  
class Join 
{ 
    static int len1 = 5; 
    static int len2 = 6; 
  
    private static string[] w1 = new string[len1]; 
    private static string[] w2 = new string[len2]; 
      
    public static void Worker1() 
    { 
        for (int i = 0; i < len1; i++) 
        { 
            w1[i] ="方法1--" + i.ToString(); 
            AddTime(1); 
            Console.WriteLine(w1[i]); 
        } 
    } 
  
    public static void Worker2() 
    { 
        for (int i = 0; i < len2; i++) 
        { 
            w2[i] = "方法2--" + i.ToString(); 
            AddTime(1); 
            Console.WriteLine(w2[i]); 
        } 
    } 
  
    //模拟代码执行时间 
    private static void AddTime(int s) 
    { 
        DateTime d = DateTime.Now; 
        while (d.AddSeconds(s) > DateTime.Now){ } 
    } 
  
    static void Main(string[] args) 
    { 
        Thread thread1 = new Thread(new ThreadStart(Worker1)); 
        Thread thread2 = new Thread(new ThreadStart(Worker2)); 
  
        thread2.Start(); 
        thread1.Start(); 
  
        //阻塞主线程,直到thread1线程终止为止 
        //这时在thread1没有执行完,后面的代码是无法执行的。 
        //当然thread2执不执行完是不管的,并且thread1与thread2是同时无顺运行的。 
        thread1.Join(); 
  
        Console.WriteLine("方法1已全部执行完成!"); 
        for (int i = 0; i < 5; i++) 
        { 
            Console.WriteLine("主线程开始执行--" + i.ToString()); 
            AddTime(2); 
        } 
    } 
}