C # restricts the number of concurrent threads routines

Source: Internet
Author: User

Implement the C # version of your own idea to limit the number of concurrent threads to the reader in need

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Threading;

Namespace WZDM. Test
{
<summary>
Restricting the number of concurrent threads routines
</summary>
public class Testthread
{
int _currentthreads = 0;
int _maxthreads = 10;

public void Test ()
{
while (true)
{
_maxthreads = new Random (). Next (1, 10);
for (int i=0; i<100; i++)
{
Limit the number here
if (_currentthreads >= _maxthreads)
Break

Open Thread
Lock (typeof (Testthread))
{
_currentthreads++;
if (_currentthreads > _maxthreads)
_currentthreads = _maxthreads;

String currentinfo = String. Format ("Thread {0}/{1}", _currentthreads, _maxthreads);
Console.WriteLine (CurrentInfo + "start");
Thread thread = new Thread (new Parameterizedthreadstart (Run));
Thread. Start (CurrentInfo);
}
}

System.Threading.Thread.Sleep (2000);
}
}

Thread Task
void Run (Object obj)
{
for (int i = 0; i < i++)
{
Console.WriteLine ("{0}:{1}", obj, i);
Thread.Sleep (100);
}
Console.WriteLine ("{0} finished", obj);

Lock (typeof (Testthread))
{
_currentthreads--;
if (_currentthreads < 0)
_currentthreads = 0;
}
}
}
}

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.