Imports System
Imports System.Threading
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)
Console.WriteLine(Now.ToLongTimeString & "线程对象创建完毕,开始执行线程")
'执行线程
mythread1.Start("线程1")
mythread2.Start("线程2")
mythread3.Start("线程3")
'等待线程完成
mythread1.Join()
mythread2.Join()
mythread3.Join()
'线程执行完毕
Console.WriteLine(Now.ToLongTimeString & "线程执行完毕!")
End Sub
Public Sub mythreadrun(ByVal data As Object)
Dim mynum As Integer
Dim jg As Integer
mynum = 20
Try
For mynum = 20 To -20 Step -1
jg = 1000 / mynum
Console.WriteLine(data & ":" & Now.ToLongTimeString & ",1000 / " & mynum & "计算结果为:" & jg)
Thread.Sleep(1)
Next
Catch
Console.WriteLine(data & ":" & Now.ToLongTimeString & "线程异常终止!")
'终止线程
Thread.CurrentThread.Abort()
End Try
End Sub
End Module
在线程中计算1000/mynum的值,其中mynum从20开始递减,到0时会出现除0异常,调用Thread.CurrentThread.Abort()
完成终止线程的操作
Try
For mynum = 20 To -20 Step -1
jg = 1000 / mynum
Console.WriteLine(data & ":" & Now.ToLongTimeString & ",1000 / " & mynum & "计算结果为:" & jg)
Thread.Sleep(1)
Next
Catch
Console.WriteLine(data & ":" & Now.ToLongTimeString & "线程异常终止!")
'终止线程
Thread.CurrentThread.Abort()
End Try