溫馨提示×

vbnet中怎么暫停指定的線程

小億
199
2023-10-20 17:48:37
欄目: 編程語言

在vb.net中,可以使用Thread.Sleep方法來暫停當(dāng)前線程的執(zhí)行。如果要暫停指定的線程,可以使用Thread.Suspend方法來暫停該線程的執(zhí)行。

以下是一個示例代碼:

Imports System.Threading

Public Class ThreadExample
    Private Shared thread1 As Thread
    Private Shared thread2 As Thread

    Public Shared Sub Main()
        ' 創(chuàng)建兩個線程
        thread1 = New Thread(AddressOf ThreadMethod1)
        thread2 = New Thread(AddressOf ThreadMethod2)

        ' 啟動線程
        thread1.Start()
        thread2.Start()

        ' 暫停線程2
        thread2.Suspend()

        ' 等待一段時間
        Thread.Sleep(5000)

        ' 恢復(fù)線程2的執(zhí)行
        thread2.Resume()

        ' 等待線程執(zhí)行完成
        thread1.Join()
        thread2.Join()
    End Sub

    Private Shared Sub ThreadMethod1()
        Console.WriteLine("Thread 1 is running")
        Thread.Sleep(1000)
        Console.WriteLine("Thread 1 is finished")
    End Sub

    Private Shared Sub ThreadMethod2()
        Console.WriteLine("Thread 2 is running")
        Thread.Sleep(1000)
        Console.WriteLine("Thread 2 is finished")
    End Sub
End Class

在上面的代碼中,我們創(chuàng)建了兩個線程thread1和thread2,并啟動它們。然后,我們使用thread2.Suspend方法暫停了線程2的執(zhí)行。之后,我們等待5秒鐘,然后使用thread2.Resume方法恢復(fù)線程2的執(zhí)行。最后,我們使用thread1.Join和thread2.Join方法等待兩個線程執(zhí)行完成。

0