Home »
VB.Net »
VB.Net Programs
VB.Net program to demonstrate the thread lock
Here, we are going to demonstrate the thread lock in VB.Net.
Submitted by Nidhi, on January 04, 2021 [Last updated : March 08, 2023]
Thread Lock in VB.Net
To implement thread locking, we will use the SyncLock block to resolve the problem of the critical section.
Program/Source Code:
The source code to demonstrate the thread lock is given below. The given program is compiled and executed successfully.
VB.Net code to demonstrate the example of thread lock
'Vb.Net program to demonstrate the thread lock.
Imports System.Threading
Module Module1
Dim obj As Object = New Object
Public Sub MyThreadFun()
SyncLock obj
Thread.Sleep(100)
Console.WriteLine(DateTime.Now)
End SyncLock
End Sub
Sub Main()
For num = 1 To 5 Step 1
Dim T As ThreadStart = New ThreadStart(AddressOf MyThreadFun)
Dim t1 As New Thread(T)
t1.Start()
Next
End Sub
End Module
Output
03-01-2021 11:09:55
03-01-2021 11:09:55
03-01-2021 11:09:55
03-01-2021 11:09:56
03-01-2021 11:09:56
Press any key to continue . . .
Explanation
In the above program, we imported the System.Threading namespace to implement multithreading in the program. After that, we created a module Module1. The Module1 contain two functions MyThreadFun() and Main().
In the MyThreadFun() function, we used the SyncLock block to lock the set of statements to avoid the problem of the critical section.
The Main() function is the entry point for the program. Here, we created threads and start them.
VB.Net Threading Programs »