C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Next: We loop again through the threads, which have now been started, and call Join on each of them.
And: The Join method causes the execution to stop until that thread terminates.
Therefore: When the loop where we call Join completes, all of the threads have completed.
SleepC# program that calls Join method on Thread
using System;
using System.Diagnostics;
using System.Threading;
class Program
{
static void Main()
{
var stopwatch = Stopwatch.StartNew();
// Create an array of Thread references.
Thread[] array = new Thread[4];
for (int i = 0; i < array.Length; i++)
{
// Start the thread with a ThreadStart.
array[i] = new Thread(new ThreadStart(Start));
array[i].Start();
}
// Join all the threads.
for (int i = 0; i < array.Length; i++)
{
array[i].Join();
}
Console.WriteLine("DONE: {0}", stopwatch.ElapsedMilliseconds);
}
static void Start()
{
// This method takes ten seconds to terminate.
Thread.Sleep(10000);
}
}
Output
DONE: 10001
And: You do not need to use Join in an array or List, but it is often desirable to.
Tip: With parallel execution, you can make many programs faster and the Join method serves an essential role in this goal.
ThreadStart