110,533
社区成员
发帖
与我相关
我的任务
分享
//互斥量
static Mutex mx = new Mutex();
//用于存储资源
static ArrayList list = new ArrayList();
//定义一个变量,标识线程索引
static int indexOfThread = 0;
//定义一个变量,用于标识当前线程的数量
static int countOfThread = 0;
static void Main(string[] args)
{
//ArrayList中存储100个数,相当于一百个资源
for (int i = 0; i < 100; i++)
{
list.Add(i);
}
//先启动10个线程
for (int i = 0; i < 10; i++)
{
mx.WaitOne();
int ii = Convert.ToInt32(list[0]);
list.RemoveAt(0);
Thread thread = new Thread(new ParameterizedThreadStart(ThreadProc));
thread.Name = "Thread " + indexOfThread++.ToString();
thread.Start(ii);
//当前的线程数目增1
countOfThread++;
Debug.WriteLine(thread.Name + "启动,当前总的线程数为: " + countOfThread);
mx.ReleaseMutex();
}
Console.ReadLine();
}
public static void ThreadProc(object i)
{
Debug.WriteLine(Thread.CurrentThread.Name + " : " + i.ToString());
Thread.Sleep(1000);
CallBack();
}
public static void CallBack()
{
mx.WaitOne();
//当前线程数自减1
countOfThread--;
//如果当前还有资源待下载,并且当前的线程的数量小于10
if (list.Count > 0 && countOfThread < 10)
{
int ii = Convert.ToInt32(list[0]);
list.RemoveAt(0);
Thread thread = new Thread(new ParameterizedThreadStart(ThreadProc));
thread.Name = "Thread " + indexOfThread++.ToString();
thread.Start(ii);
//当前的线程数目增1
countOfThread++;
Debug.WriteLine(thread.Name + "启动,当前总的线程数为: " + countOfThread);
}
mx.ReleaseMutex();
}