c# 创建线程,然后等第一个走完再走第二个
时间: 2023-10-28 12:33:06 浏览: 48
在C#中可以使用Thread类创建线程,可以通过调用Thread类的Join()方法来等待线程执行完毕后再继续执行下面的代码。例如:
```csharp
using System;
using System.Threading;
class Program {
static void Main() {
Thread t1 = new Thread(new ThreadStart(FirstThread));
Thread t2 = new Thread(new ThreadStart(SecondThread));
t1.Start();
t1.Join(); //等待t1执行完毕
t2.Start();
}
static void FirstThread() {
Console.WriteLine("First thread is running...");
//模拟耗时操作
Thread.Sleep(5000);
Console.WriteLine("First thread is done.");
}
static void SecondThread() {
Console.WriteLine("Second thread is running...");
//模拟耗时操作
Thread.Sleep(3000);
Console.WriteLine("Second thread is done.");
}
}
```
在这个例子中,首先创建了两个线程t1和t2,然后启动t1线程并等待其执行完毕后再启动t2线程。在FirstThread方法中模拟了一个耗时操作,让线程执行5秒钟,然后输出一条信息。在SecondThread方法中也模拟了一个耗时操作,让线程执行3秒钟,然后输出一条信息。在Main方法中,首先启动了t1线程,然后调用t1.Join()方法等待t1线程执行完毕后再启动t2线程。由于t1线程执行了5秒钟,所以t2线程要等待t1线程执行完毕后才能开始执行,而t2线程只执行了3秒钟,所以在t1线程输出信息之后就会输出t2线程的信息。