Thread.Join

https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.join?view=netframework-4.7.2

https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.join?view=netframework-4.7.2#System_Threading_Thread_Join_System_Int32_

 

https://www.cnblogs.com/nzbbody/archive/2012/03/06/2381524.html

MSDN的解释:阻塞调用线程,直到某个线程终止时为止。首先明确几个问题:

1、一个进程由一个或者多个线程组成,线程之间有可能会存在一定的先后关系和互斥关系。多线程编程,首先就是要想办法划分线程,减少线程之间的先后关系和互斥关系,这样才能保证线程之间的独立性,各自工作,不受影响。Google的MapReduce核心思想就是尽量减少线程之间的先后关系和互斥关系。

2、无论如何地想办法,线程之间还是会存在一定的先后关系和互斥关系,这时候可以使用Thread.Join方法。

3、一个线程在执行的过程中,可能调用另一个线程,前者可以称为调用线程,后者成为被调用线程。

4、Thread.Join方法的使用场景:调用线程挂起,等待被调用线程执行完毕后,继续执行。

5、被调用线程执行Join方法,告诉调用线程,你先暂停,我执行完了,你再执行。从而保证了先后关系。

6、考虑一种有意思的情况:在当前线程内调用Thread.CurrentThread.Join() 会出现什么情况?分析:假设当前线程为A,此时调用线程为A,被调用线程也为A,由于调用线程A暂停,被调用线程A(也就是调用线程A)永远不会执行完毕,造成死锁。

 

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

 首先来看一下有关的概念: 我们执行一个.exe文件实际上就是开启了一个进程,同时开启了至少一个线程,

但是真正干活的是线程,就好比一个Team有好几个人,但是真正干活的是人不是Team. 

 

具体到代码来说,以Console Application为例:程序Test.exe从Main函数开始运行,实际上是有一个线程

在执行Main函数,我们称作MainThread.假如我们在Main函数中声明了一个Thread,称作NewThread,并且调用了

NewThread.Start()的方法,那么 MainThread在处理Main函数里面的代码时遇到NewThread.Start()时,就会

去调用NewThread.

       基于上面的讨论,我们可以得出结论:在我们刚才的例子中the calling thread就是MainThread,而a thread

指的恰恰就是MainThread调用的NewThread线程。 

 

带上参数的Thread.Join

Join(Int32) is a synchronization method that blocks the calling thread (that is, the thread that calls the method) until either the thread whose Join method is called has completed or the time-out interval has elapsed. In the following example, the Thread1 thread calls the Join() method of Thread2, which causes Thread1 to block either until Thread2 has completed or 2 seconds have elapsed.  

 

If Timeout.Infinite is specified for the millisecondsTimeout parameter, this method behaves identically to the Join() method overload, except for the return value.

If the thread has already terminated when Join is called, the method returns immediately.

This method changes the state of the calling thread to include ThreadState.WaitSleepJoin. You cannot invoke Join on a thread that is in the ThreadState.Unstarted state.

 

在验证连接数据库的时候,可以使用这个。设定1个超时时间,然后先开一个线程尝试连接数据库。

 

posted @ 2019-02-19 16:41  ChuckLu  阅读(325)  评论(0编辑  收藏  举报