我们接着前面的例子讲述,这个例子的功能是3个线程共同完成对一个数的连续减法运算,在前面的例子,我们在每个线程做完减法运算后都加入了thread.sleep,以使线程能将执行机会给其它线程,同时也使得在这个例子一般不会发生线程同步问题,我们去掉sleep,可以发现由于没有解决同步问题,有线程读到了脏数据。
代码为:
Imports System
Imports System.Threading
Imports System.Diagnostics
Imports System.Diagnostics.ThreadState
Module Module1
Sub Main()
Dim mythread1 As Thread
Dim mythread2 As Thread
Dim mythread3 As Thread
'创建线程对象
mythread1 = New Thread(AddressOf mythreadrun)
mythread2 = New Thread(AddressOf mythreadrun)
mythread3 = New Thread(AddressOf mythreadrun)
mythread1.Name = "thread_1"
mythread2.Name = "thread_2"
mythread3.Name = "thread_3"
'设置线程是否允许动态优先级
Console.WriteLine(Now.ToLongTimeString & "线程对象创建完毕,开始执行线程")
Dim myprocess As Process = Process.GetCurrentProcess()
Console.WriteLine("进程名称:" & myprocess.ProcessName)
'执行线程
mythread1.Start(myprocess)
mythread2.Start(myprocess)
mythread3.Start(myprocess)
'等待线程完成
mythread1.Join()
mythread2.Join()
mythread3.Join()
'线程执行完毕
Console.WriteLine(Now.ToLongTimeString & "线程执行完毕!")
End Sub
Public Sub mythreadrun(ByVal myprocess As Object)
Dim mynum As Double
Static Dim jg As Double = 100
Try
For mynum = 1 To 2 Step 0.1
jg -= mynum
Console.WriteLine(Thread.CurrentThread.Name & "==>" & Now.ToLongTimeString & "=>" & (jg + mynum) & "-" & mynum & ",计算结果为:" & jg)
' Thread.Sleep(50)
Next
Catch
Console.WriteLine(Thread.CurrentThread.Name & " " & Now.ToLongTimeString & "线程异常终止!")
'终止线程
Thread.CurrentThread.Abort()
Finally
Console.WriteLine(Thread.CurrentThread.Name & "优先级: " & Thread.CurrentThread.Priority.ToString)
Console.WriteLine(Thread.CurrentThread.Name & " " & Now.ToLongTimeString & "线程运行完毕!")
End Try
End Sub
End Module
我们将上述代码的thread.sleep(50)的注释去掉,可以发现程序正常执行了
sleep掩盖了同步问题的发生