Use of Thread Pool

Source: Internet
Author: User
Purpose:
Actively and effectively process busy customer segment requests.
Practice:
Enable multiple threads and process client segment requests in the form of traffic delivery.
This includes creating your own thread pool and using the thread pool provided by the system.

Example: Create your own Thread Pool

Using system. Threading;

Class mythreadpool
{
Reusablethread [] m_threadpool;

Public mythreadpool (INT psize)
{
M_threadpool = new reusablethread [psize];

For (INT I = 0; I <psize; I ++)
{
M_threadpool [I] = new reusablethread ();
}
}

Public reusablethread getthread ()
{
Lock (this)
{
Reusablethread vthread = getavailablethread ();

Return vthread;
}
}

Public reusablethread getavailablethread ()
{
Reusablethread vreturnthread = NULL;

Foreach (reusablethread vthread in m_threadpool)
{
If (vthread. isavailable)
{
Vthread. isavailable = false;
Vreturnthread = vthread;

Break;
}
}

Return vreturnthread;
}

Public void putthread (reusablethread pthread)
{
Lock (this)
{
Pthread. isavailable = true;
}
}
}
// ---------------------------------- Reusablethread -------------------
Public Delegate void startupmethod ();
Class reusablethread
{
Private thread m_thread;
Public bool isavailable = true;
Private startupmethod m_startupmethod;

Public reusablethread ()
{
M_thread = new thread (New threadstart (commonstart ));
}

Public void join ()
{
M_thread.join ();
}

Public void run (startupmethod pstartupmethod)
{
M_startupmethod = pstartupmethod;
M_thread.start ();
}

Public void commonstart ()
{
If (m_startupmethod! = NULL)
{
M_startupmethod ();
M_startupmethod = NULL;
}
}
}

// ----------------------------- Excute code ----------------
Public class mainapp
{
Public void runwiththread ()
{
Mythreadpool vpool = new mythreadpool (20 );
Reusablethread vthead = vpool. getthread ();
If (vthread = NULL)
{
Return;
}
Else
{
Vthread. Run (New startupmethod (mycode ));
Vthread. Join ();
Vpool. putthread (vthread );
}
}

Public void mycode ()
{
Thread. Sleep (2000 );
}
}

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.