胖在一方

出得厅堂入得厨房的胖子

导航

当为多线程的应用程序创建singleton设计模式时,需要确保它们都是线程安全的。

 1Imports System.Threading
 2

 3Public 
Class Singleton_thread
 4

 5    'private member

 6    Private Shared m_Instance As Singleton_thread
 7    Private Shared m_TimeOfBirth As String

 8    Private Shared m_Mutex As New Mutex
 9    Private 
Sub New()
10        Console.WriteLine(String.Format("Creating Singleton at {0}"
, Now.ToLongTimeString))
11        m_TimeOfBirth =
 Now.ToLongTimeString
12    End Sub

13
14    'public member

15    Public Shared Function GetInstance() As Singleton_thread
16
        m_Mutex.WaitOne()
17        If m_Instance Is Nothing Then

18            m_Instance = New Singleton_thread
19        End If

20        m_Mutex.ReleaseMutex()
21        Return
 m_Instance
22    End Function

23    
24

25

26End Class