Imports system
Imports system.threading
Public Module Threadsample
Public balance as integer = 1000
Sub main ()
DIM Account as account = new account ()
DIM DepositEmbalance1 as DepositEbalance = New_
DepositEbalance (Account, 1000, "Customer 1")
DIM depositebalance2 as Depositebalance = new _
DepositEbalance (Account, 1000, "Customer 2")
DIM T1 as thread = new _
Thread (addressof depositsbalance1.depositeamount)
DIM T2 as thread = new _
Thread (Addressof DepositEbalance2.DepositeAmount)
T1.Start ()
T2.Start ()
Try
'Blocking the thread until a thread is terminated
t1.join ()
't2.join ()
Catch e as exception
Console.write (e.tostring ())
Finally
'Do nothing
END TRY
End Sub
Public Class Account
Private balanceamount as integer
Public Sub Deposit (Byval Amount AS Integer, _
Byval Message As String)
Console.writeline (Message &_
"Depositing Amount" & Amount)
Console.writeline (Message & "Checking Previous Balance")
The 'Monitor class controls access to the object by granting the object lock to a single thread. Object locks provide restrictions on access code blocks (commonly referred to as critical regions). When a thread has an object's lock, other threads cannot get the lock. You can also use Monitor to make sure that any other thread is not allowed to access the application code section executed by the owner of the lock unless another thread is using other locked objects to perform the code.
'The beginning of the critical area, guarantees that there can be only one thread to operate
Monitor.Enter (me)
BalanceAmount = getBalance ()
Console.writeline (Message &_
"Previous Balance in Account" & balanceamount)
BalanceAmount = Amount
Console.writeline (Message &_
"Updating Balance in Account")
SetBalance (BalanceAmount)
Monitor.exit (ME)
'Remember the end of the Urban
Console.writeline (Message & "Update Balance" & balance)
End Sub
Private function getBalance () AS integer
Try
'Block the current thread to block the number of milliseconds
Thread.sleep (1000)
Catch e as exception
Console.writeline (E.TOString ()) Finally
'Do nothing
END TRY
Return balance
END FUNCTION
Private sub setbalance (Byval Amount AS Integer)
Try
'Block the current thread to block the number of milliseconds
Thread.sleep (1000)
Catch e as exception
Console.writeLine (E.TOString ())
Finally
'Do nothing
END TRY
Balance = Amount
End Sub
END CLASS
Public class depositsbalance
Private Account As Account
PRIVATE AMOUNT AS INTEGER
Private Message As String
Public Sub New (Byref Account As Account, _
BYVAL AMOUNT AS integer, byval message as string
Mybase.new ()
Me.account = Account
Me.amount = Amount
Me.Message = Message
End Sub
Public Sub DepositEamount ()
Account.Deposite (Amount, Message)
End Sub
END CLASS
End module