在上一章学习过后,我们肯定希望能控制线程有序,Join和Sleep可以通过阻塞线程成达到这一目的,下面我们开始学习Join和Sleep方法。
Join方法:等待另一个线程完成。
示例如下:
namespace JoinANDsleep
{
class Program
{
static Thread thread1, thread2;
public static void Main(string[] args)
{
thread1 = new Thread(ThreadProc);
thread1.Name = "Thread1";
thread1.Start();
thread2 = new Thread(ThreadProc);
thread2.Name = "Thread2";
thread2.Start();
Console.ReadKey();
}
private static void ThreadProc()
{
Console.WriteLine($"\nCurrent thread :{Thread.CurrentThread.Name}");
if (Thread.CurrentThread.Name=="Thread1"&&thread2.ThreadState!=ThreadState.Unstarted)
{
thread2.Join();
}
Thread.Sleep(2000);
Console.WriteLine($"\nCurrent thread: {Thread.CurrentThread.Name}");
Console.WriteLine($"Thread1: {thread1.ThreadState}");
Console.WriteLine($"Thread2: {thread2.ThreadState}");
}
}
}
这里的执行顺序是,创建线程一,开始线程一,然后进入到委托的函数中,打印出最近的线程名称,这里打印的是线程一,然后再判断是否满足条件,与此同时,线程二可能已经开始了,并满足这里的条件,线程一就要等到线程二执行完成后才执行,所以打印出的最终结果,应该是
Current thread :Th

本文介绍了Java多线程中Join和Sleep的方法。Join用于等待另一个线程完成,确保线程有序执行;Sleep则可以暂停当前线程,允许其他线程执行。Join可设置超时,Sleep(0)能立即让出线程执行权,两者都涉及内核级的线程阻塞操作。
 Join和Sleep&spm=1001.2101.3001.5002&articleId=108987389&d=1&t=3&u=6b7e664386374af8b36faee4d69553f7)
1739

被折叠的 条评论
为什么被折叠?



