Join and Sleep
- 调用Join方法,就可以等待另一个线程结束。 AB两个线程,如果B.Join() 那就等待B执行完成才执行A。
- 例子(join) ```csharp using System; using System.Threading;
namespace ThreadTest { class Program { private static Thread thread1, thread2; static void Main() { // 创建两个线程命名并执行 thread1 = new Thread(ThreadProc); thread1.Name = “Thread1”; thread1.Start();
thread2 = new Thread(ThreadProc);
thread2.Name = "Thread2";
thread2.Start();
}
static void ThreadProc()
{
Console.WriteLine("\nCurrent thread:{0}", Thread.CurrentThread.Name);
if (Thread.CurrentThread.Name == "Thread1" && thread2.ThreadState != ThreadState.Unstarted)
{
thread2.Join();
}
Thread.Sleep(2000);
Console.WriteLine("\nCurrent thread:{0}", Thread.CurrentThread.Name);
Console.WriteLine("Thread1:{0}", thread1.ThreadState);
Console.WriteLine("Thread2:{0}\n", thread2.ThreadState);
}
}
}
![image.png](https://cdn.nlark.com/yuque/0/2020/png/1624034/1593094689546-e78426ba-3867-4cf4-a000-11d6dc9edbbd.png#crop=0&crop=0&crop=1&crop=1&height=279&id=Atyaw&margin=%5Bobject%20Object%5D&name=image.png&originHeight=279&originWidth=304&originalType=binary&ratio=1&rotation=0&showTitle=false&size=15959&status=done&style=stroke&title=&width=304)
<a name="7FZOB"></a>
## 添加超时
- 调用Join的时候,可以设置一个超时,用毫秒或者TimeSpan都可以(Join重载。如果调用Join的时候不带参数是void,带参数的话返回值是bool类型)。
- 如果返回时true,那就是线程结束了;如果超时了就返回false。
```csharp
using System;
using System.Threading;
namespace ThreadTest
{
class Program
{
private static TimeSpan waitTime = new TimeSpan(0, 0, 1);
static void Main()
{
Thread newThread = new Thread(Work);
newThread.Start();
if (newThread.Join(waitTime + waitTime))
{
Console.WriteLine("线程结束.");
}
else
{
Console.WriteLine("连接超时.");
}
}
static void Work()
{
Thread.Sleep(waitTime);
}
}
}
- Thread.Sleep()方法会暂停当前的线程,并等待一段时间。
- 注意:
- Thread.Sleep(0)这样调用会导致线程立即放弃本身当前的时间片,自动将CPU移交给其他线程。
- Thread,YieId做同样的事情,但是它指挥把执行交给同一处理器上的其它线程。
其它
- Sleep(0)或YieId有时在高级性能调试的生产代码中很有用。它也是一个很好的诊断工具,有助于发现线程安全问题:
- 如果在代码中的任何地方插入Thread.YieId就破坏了程序,那么你的程序几乎肯定有bug。