Imports System.Threading
Module Tester
Sub Main()
Dim holdInteger As New Buffer()
Dim producer As New Producer(holdInteger)
Dim consumer As New Consumer(holdInteger)
Dim producerThread As New Thread(AddressOf producer.Produce)
Dim consumerThread As New Thread(AddressOf consumer.Consume)
producerThread.Name = "Producer"
consumerThread.Name = "Consumer"
producerThread.Start()
consumerThread.Start()
End Sub
End Module
Public Class Producer
Private buffer As Buffer
Public Sub New(ByVal sharedObject As Buffer)
buffer = sharedObject
End Sub ' New
Public Sub Produce()
Dim count As Integer
For count = 1 To 4
Thread.Sleep(4000)
buffer.Buffer = count
Next
Console.WriteLine(Thread.CurrentThread.Name & _
" done producing." & vbCrLf & "Terminating " & _
Thread.CurrentThread.Name & ".")
End Sub
End Class
Public Class Consumer
Private buffer As Buffer
Public Sub New(ByVal sharedObject As Buffer)
buffer = sharedObject
End Sub ' New
Public Sub Consume()
Dim count, sum As Integer
For count = 1 To 4
Thread.Sleep(300)
sum += buffer.Buffer
Next
Console.WriteLine(Thread.CurrentThread.Name & _
" read values totaling: " & sum & "." & vbCrLf & _
"Terminating " & Thread.CurrentThread.Name & ".")
End Sub
End Class
Public Class Buffer
Private mBuffer As Integer = -1
Property Buffer() As Integer
Get
Console.WriteLine(Thread.CurrentThread.Name & _
" reads " & mBuffer)
Return mBuffer
End Get
Set(ByVal Value As Integer)
Console.WriteLine(Thread.CurrentThread.Name & _
" writes " & Value)
mBuffer = Value
End Set
End Property ' Buffer
End Class
Consumer reads -1
Consumer reads -1
Consumer reads -1
Consumer reads -1
Consumer read values totaling: -4.
Terminating Consumer.
Producer writes 1
Producer writes 2
Producer writes 3
^CTerminate batch job (Y/N)? ^Cn