我们下面通过WaitHandle.WaitOne 方法和EventWaitHandle.Set 方法来实现
EventWaitHandle.Set 方法
将事件状态设置为终止状态,允许一个或多个等待线程继续。
WaitHandle.WaitOne方法
阻止当前线程,直到当前 WaitHandle收到信号为止。
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
Static autoEvent As New AutoResetEvent(True)
Try
For mynum = 1 To 2 Step 0.1
autoEvent.WaitOne()
'autoEvent.Reset()
jg -= mynum
Console.WriteLine(Thread.CurrentThread.Name & "==>" & Now.ToLongTimeString & "=>" & (jg + mynum) & "-" & mynum & ",计算结果为:" & jg)
autoEvent.Set()
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
注意这部分代码
autoEvent.WaitOne()
'autoEvent.Reset()
jg -= mynum
Console.WriteLine(Thread.CurrentThread.Name & "==>" & Now.ToLongTimeString & "=>" & (jg + mynum) & "-" & mynum & ",计算结果为:" & jg)
autoEvent.Set()
为什么将autoEvent.Reset()注释,因为当线程等待到资源后,即当前 WaitHandle 收到信号后,会自动将状态置为非终止
运行效果如下:
从上图可以看出,我们用多个线程完成对某个数的减法运算真正成功了,而且解决了同步问题