欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

VB.NET并行与分布式编程(2)-线程终止

程序员文章站 2022-04-29 15:21:54
...
 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

 VB.NET并行与分布式编程(2)-线程终止
            
    
    博客分类: .net&silverlight  

在线程中计算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

 

  • VB.NET并行与分布式编程(2)-线程终止
            
    
    博客分类: .net&silverlight  
  • 大小: 72.9 KB