我正在尝试将一些多线程应用到我的代码中,因此我试图练习一些简单的任务。在下面的简单代码中,我希望每个线程都取一个计数器(m)的值,然后增加它的值,然后使用之前取的值做一些事情,并将它的结果复制到一个列表(listL)中。不幸的是,我不能阻止线程两次采用相同的值...这可能很简单,但我找不到合适的解决方案...提前谢谢..
马里奥
imports System.Threading
Module Module1
Public m As UShort = 0
Dim listL As New List(Of Integer)
Sub Main()
Dim t1 As New Thread(AddressOf TestMultiThreading)
Dim t2 As New Thread(AddressOf TestMultiThreading)
t1.Start("a")
t2.Start("b")
t1.Join()
t2.Join()
For m As Integer = 0 To listL.Count - 1
For n As Integer = m + 1 To listL.Count - 1
If listL(n) = listL(m) Then Debug.Print("same {0} {1}", n, m)
Next n
Next m
listL.Clear()
End Sub
Public Sub TestMultiThreading(ByVal X As Char)
Dim lobj1 As New Object
Dim p As Integer
Do While m < 100
SyncLock lobj1
p = m
m += 1
End SyncLock
' various calculations ...
' eventually
listL.Add(m)
Loop
lobj1 = Nothing
Debug.WriteLine("end " & X)
End Sub
End Module