多线程小结(3)

来源

【多线程-Join()方法】

一. 什么时候使用Join()方法:

当一个线程操作需要等待另一个线程执行完毕之后才能继续进行时,使用Join()方法。Join方法会等到使用该方法的线程结束后再执行下面的代码。

就是当A线程,要等到B线程完成之后再执行A的话,就用到Join方法了。

因为是得等到B线程先执行,所以是:B.Join();

 1 namespace ThreadJoin
 2 {
 3     class Program
 4     {
 5         private static Thread subthread;
 6         private static string name = "";  
 7         static void Main(string[] args)
 8         {
 9             Console.WriteLine("xxxxxx:");
10             //声明一个新的线程,这里新的线程去执行Getshow的方法
11             //说一点哈:这个声明一个方法,逐步执行的话,他不会进GetShow方法里面,直接跳过
12             subthread = new Thread(new ThreadStart(GetShow));
13             Console.WriteLine("xxxxxx:");
14             subthread.Start();  //开启线程  
15             subthread.Join();//等待>当subthread线程执行完毕之后,才执行下面的语句 
16             // Console.WriteLine();这样的代码,是主线程的代码
17             //本来执行过 subthread.Join(); 后要执行下面的console的,但是现在因为加入了Join
18             //所以得先去执行GetShow方法了。
19             Console.WriteLine("xxxxxx:");
20             Console.WriteLine("姓名:" + name);
21 
22             Console.WriteLine("主线程");
23 
24 
25             Console.ReadKey();
26 
27         }
28         static void GetShow()
29         {
30             Console.WriteLine("输入姓名:");
31 
32             name = Console.ReadLine();
33             Console.WriteLine("次线程");
34         }  
35     }
36 }
View Code

Join()方法可以用于简单线程项目的线程同步。

简单的理解,结识:假如有多个线程:但是我想先让B线程跑,B跑完后,其他的再跑;

那就给B:B.Join;

猜你喜欢

转载自www.cnblogs.com/ZkbFighting/p/9033740.html