[Repeat the topic] The simplest single-piece Mode

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.