C# 线程等待:使用 Join() 方法实现线程间同步
在 C# 中,可以使用 Thread 类的 Join() 方法使一个线程等待另一个线程完成。例如,可以在一个线程中调用 Join() 方法,使当前线程等待另一个线程完成后再继续执行。
示例代码:
Thread t1 = new Thread(() => {
Console.WriteLine('Thread 1 started');
Thread.Sleep(5000); // 模拟耗时操作
Console.WriteLine('Thread 1 finished');
});
Thread t2 = new Thread(() => {
Console.WriteLine('Thread 2 started');
t1.Join(); // 等待 t1 线程完成
Console.WriteLine('Thread 2 finished');
});
t1.Start();
t2.Start();
输出结果:
Thread 1 started
Thread 2 started
Thread 1 finished
Thread 2 finished
原文地址: https://www.cveoy.top/t/topic/ngNX 著作权归作者所有。请勿转载和采集!