I have a MultiThreading issue and conceptual question using Visual Basic (but it applies to almost all languages). I have a function which:
- creates 5 instances of a class which each spawns a thread which calls a function
- The Function sleeps for X milli-seconds
- prints to console
- then terminates the thread
How can I ensure all instances of the class gets a chance to finish before main cuts it off??
Most relevant help through research: How do I pause main() until all other threads have died?
Here is my code:
Imports System
Imports System.Threading
Imports System.Collections.Generic
Module Module1
Private raceTrack As New List(Of RaceCar)
Sub Main()
CreateRace()
'Main() would quit when the 5 car objects are created =[
'How do I make sure Main will not exit until all racecars are done?
End Sub
Sub CreateRace()
For index As Integer = 1 to 5
raceTrack.Add(new RaceCar(index))
Next
End Sub
Public Class RaceCar
Private testThread as Thread = New Thread(AddressOf StartEngine)
Private carId as Integer
Public Sub New(ByVal carNumber as Integer)
me.carId = carNumber
Me.TestThread.Start()
Me.TestThread.Join()
End Sub
Public Sub StartEngine()
Console.WriteLine(String.Format("Car#{0} is going!", Me.carId))
Thread.Sleep(100*Me.carId)
Console.WriteLine(String.Format("Car#{0} is DONE!", Me.carId))
End Sub
End Class
End Module