
























为了设计一个自己的“线程池”我给自己做了这么个东西。
这段程序能产生起始的10个线程,这10个线程启动后,每结束一个线程就会有另外一个线程补充进去,这样始终保持有10个线程在活动。
代码如下:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;

namespace ThreadPool
{
public class Program
{
ArrayList alThread = new ArrayList();

static void Main(string[] args)
{
Program p = new Program();
p.threadtest();
}

public void threadtest()
{
for (int i = 0; i < 10; i++)
{
threadok to = new threadok();
to.threadid = i;
to.finished = new threadok.Finished(FinishOne);
ThreadStart starter = new ThreadStart(to.run);
Thread thread = new Thread(starter);
alThread.Add(to);
thread.Start();

}
Console.WriteLine("OK!");
Console.ReadLine();
}


public void FinishOne(threadok to)
{
//
Console.WriteLine("ThreadID:{0},Finished", to.threadid.ToString());
alThread.Remove(to);

if (alThread.Count < 10)
{
Random rnd = new Random();

threadok toa = new threadok();
toa.threadid = rnd.Next(100);
toa.finished = new threadok.Finished(FinishOne);
ThreadStart starter = new ThreadStart(toa.run);
Thread thread = new Thread(starter);
alThread.Add(toa);
thread.Start();
}
}
}

public class threadok
{
public delegate void Finished(threadok to);
public Finished finished;

public int threadid;

public void run()
{
Console.WriteLine("ThreadID:{0}", threadid.ToString());
Thread.Sleep(1000);
finished(this);
}

}
}


最后,这个所谓的“线程池”跟正宗的“线程池”不可同日而语。
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。