Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create multiple threads and wait for all of them to complete

How can I create multiple threads and wait for all of them to complete?

like image 634
user496949 Avatar asked Nov 16 '10 03:11

user496949


People also ask

Does Java wait for all threads to finish?

Behind the scenes it is using default JVM's fork join pool which means that it will wait for all the threads to finish before continuing.

How does one ensure thread Synchronisation such that all threads wait until all threads arrive?

Barriers. Barriers are a synchronization mechanism that can be used to coordinate multiple threads working in parallel. A barrier allows each thread to wait until all cooperating threads have reached the same point, and then continue executing from there.


1 Answers

It depends which version of the .NET Framework you are using. .NET 4.0 made thread management a whole lot easier using Tasks:

class Program {     static void Main(string[] args)     {         Task task1 = Task.Factory.StartNew(() => doStuff());         Task task2 = Task.Factory.StartNew(() => doStuff());         Task task3 = Task.Factory.StartNew(() => doStuff());          Task.WaitAll(task1, task2, task3);                 Console.WriteLine("All threads complete");     }      static void doStuff()     {         //do stuff here     } } 

In previous versions of .NET you could use the BackgroundWorker object, use ThreadPool.QueueUserWorkItem(), or create your threads manually and use Thread.Join() to wait for them to complete:

static void Main(string[] args) {     Thread t1 = new Thread(doStuff);     t1.Start();      Thread t2 = new Thread(doStuff);     t2.Start();      Thread t3 = new Thread(doStuff);     t3.Start();      t1.Join();     t2.Join();     t3.Join();      Console.WriteLine("All threads complete"); } 
like image 167
Greg Sansom Avatar answered Sep 29 '22 09:09

Greg Sansom