Visual Basic.NET实现双检锁(DCL)模式(四)
 问答题答案

  第1题答案、Mutex改写同步化代码清单5,结果如下:

Public Class Factory2A
Private Shared instance As Product
Private Shared m As Mutex = New Mutex()

Private Sub New()
System.Console.WriteLine("Factory object is created.")
End Sub

Public Shared Function GetInstance() As Product
Thread.Sleep(10)
m.WaitOne()

If (instance Is Nothing) Then
instance = New Product()
End If

m.ReleaseMutex()
Return instance
End Function
End Class

代码清单10、二重检查的线程安全的Singleton类

  第2题答案、Monitor对象提供针对一个资源对象的同步锁。使用Monitor对象改写代码清单5,结果为:

Public Class Factory2B
Private Shared instance As Product

Private Sub New()
System.Console.WriteLine("Factory object is created.")
End Sub

Public Shared Function GetInstance() As Product
Thread.Sleep(10)
Monitor.Enter(GetType(Factory2B))

If (instance Is Nothing) Then
instance = New Product()
End If

Monitor.Exit(GetType(Factory2B))
Return instance
End Function
End Class

代码清单11、二重检查的线程安全的Singleton类

  第3题答案、使用了SyncLock的版本如下:

Public Class Factory2C
Private Shared instance As Product

Private Sub New()
System.Console.WriteLine("Factory object is created.")
End Sub

Public Shared Function GetInstance() As Product
Thread.Sleep(10)
SyncLock (GetType(Factory2C))
If (instance Is Nothing) Then
instance = New Product()
End If
End SyncLock

Return instance
End Function
End Class

代码清单12、二重检查的线程安全的Singleton类

  第4题答案、使用Monitor对象改写后的双检锁工厂类为:

Public Class Factory3A
Private Shared instance As Product

Public Shared Function GetInstance() As Product
Thread.Sleep(10)

If (instance Is Nothing) Then
Monitor.Enter(GetType(Factory3A))
If (instance Is Nothing) Then
instance = New Product()
End If
Monitor.Exit(GetType(Factory3A))
End If
Return instance
End Function
End Class

代码清单13、二重检查的线程安全的Singleton类

  第5题答案、使用SyncLock改写后的双检锁工厂类为;

Public Class Factory3B
Private Shared instance As Product

Public Shared Function GetInstance() As Product
Thread.Sleep(10)

If (instance Is Nothing) Then
SyncLock (GetType(Factory3B))
If (instance Is Nothing) Then
instance = New Product()
End If
End SyncLock
End If
Return instance
End Function
End Class