My friend went to the interview that day and wrote a simple Singleton question. Many people in the blog Park have already written a backup copy.
Private constructor has previously been written. [Read More] private constructor.
Code: Class Program
{
Static void main (string [] ARGs)
{
Factory FT1 = factory. getfactory ();
Ft1.recordcount ();
Ft1.display ();
Factory FT2 = factory. getfactory ();
Ft2.recordcount ();
Ft2.display ();
Console. Read ();
}
}
Public class factory
{
Private Static factory _ factory;
Private Static object objlock = typeof (factory );
Private long longcount;
Private Factory ()
{
Longcount = 0;
}
Public static factory getfactory ()
{
Lock (objlock)
{
If (object. Equals (null, _ factory ))
{
_ Factory = new factory ();
}
Return _ factory;
}
}
Public void recordcount ()
{
Lock (objlock)
{
Longcount ++;
}
}
Public void display ()
{
Console. writeline (longcount );
}
}
Hey, there is almost no comment.
In addition:
Single Piece and thread: this may happen. Two threads may initialize a single piece at the same time. Assume that one method finds that one piece does not exist. At this time, the other thread starts to execute, this thread also finds that this single piece does not exist, so both methods need to initialize this single piece. Therefore, the lock mechanism should be added to wait for the other thread to wait until the single piece is initialized, the thread finds that a single piece already exists.