Thread.Start
Learn to start threads with Thread.Start and wait with Join.
Start and Join
Thread.Start() begins running a thread; the call returns immediately while the thread runs in the background. Thread.Join() blocks the caller until the target thread finishes.
Used together: Start to begin, Join to wait — this is the basis of simple synchronization. Join accepts a timeout: t.Join(1000) waits at most 1 second.
Ordering with Join
To wait for several threads in sequence, write t1.Join(); t2.Join();. When all Join calls return, the main thread continues.
This is a simple way to gather parallel work and combine results. If a thread never ends, Join waits forever; so for safety, a timeout Join may be preferred.
Exercise Wait for two threads in sequence
Create Thread t1 = new Thread(() => { }); and Thread t2 = new Thread(() => { });. Start both with Start(), then wait with t1.Join(); t2.Join();. Finally print Console.WriteLine("Done");.
Show example solution
Thread t1 = new Thread(() => { }); Thread t2 = new Thread(() => { }); t1.Start(); t2.Start(); t1.Join(); t2.Join(); Console.WriteLine("Done");
Example solution:
using System;
using System.Threading;
class Program
{
static void Main()
{
Thread t1 = new Thread(() => { });
Thread t2 = new Thread(() => { });
t1.Start();
t2.Start();
t1.Join();
t2.Join();
Console.WriteLine("Done");
}
}
Test yourself
-
The Join call
t.Start(); t.____();Show answer
t.Start(); t.Join(); -
What does Thread.Join() do?
- Starts the thread
- Blocks the caller until the target ends
- Cancels the thread
- Creates a new thread
Show answer
Blocks the caller until the target ends — Correct. Join blocks the caller.
-
Match the Thread methods
- Start()
- Starts the thread
- Join()
- Waits for completion
- Join(1000)
- Timeout wait
- Sleep(500)
- Pause for a duration