我有一個使用Visual Basic的多線程問題和概念問題(但它幾乎適用於所有語言)。 我有一個函數:如何確保主要終止之前完成課程的實例?
- 創建類的5個實例,其中每個派生它調用一個功能
- 的作用休眠X毫秒的螺紋
- 打印到控制檯
- 然後終止線程
如何確保班級的所有實例都有機會在主要切斷之前完成?通過研究
最相關的幫助:How do I pause main() until all other threads have died?
這裏是我的代碼:
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
您可以在您的實例化的每個類的調用程序中增加一個「counter」,並在每個類的線程終止時爲每個類引發一個「Event」。然後在你的調用程序中創建一個''EventHandler'來減少'counter'。當counter = 0時,所有的線程都被終止。 – 2012-02-14 20:41:07
@Michael這聽起來不錯,我會試試看。 – Ken 2012-02-14 20:48:37
都鐸王朝的回答對你代碼中的缺陷有一個好的看法。 – 2012-02-14 20:50:33