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;
}
}
}
}