(点击上方蓝字,可快速 publicintCooki; publicSomStat(intiCooki) { Cooki=iCooki; } } publicclassAlpha { publicHashtablHashCount; publicManualRstEvntvntX; publicstaticintiCount=0; publicstaticintiMaxCount=0;
publicAlpha(intMaxCount) { HashCount=nwHashtabl(MaxCount); iMaxCount=MaxCount; } //线程池里的线程将调用Bta()方法 publicvoidBta(Objctstat) { //输出当前线程的hash编码值和Cooki的值 Consol.WritLin({0}{1}:,Thrad.CurrntThrad.GtHashCod(),((SomStat)stat).Cooki); Consol.WritLin(HashCount.Count=={0},Thrad.CurrntThrad.GtHashCod()=={1},HashCount.Count,Thrad.CurrntThrad.GtHashCod()); lock(HashCount) { //如果当前的Hash表中没有当前线程的Hash值,则添加之 if(!HashCount.ContainsKy(Thrad.CurrntThrad.GtHashCod())) HashCount.Add(Thrad.CurrntThrad.GtHashCod(),0); HashCount[Thrad.CurrntThrad.GtHashCod()]= ((int)HashCount[Thrad.CurrntThrad.GtHashCod()])+1; } intiX=; Thrad.Slp(iX); //Intrlockd.Incrmnt()操作是一个原子操作,具体请看下面说明 Intrlockd.Incrmnt(rfiCount); if(iCount==iMaxCount) { Consol.WritLin(); Consol.WritLin(SttingvntX); vntX.St(); } } } publicclassSimplPool { publicstaticintMain(string[]args) { Consol.WritLin(ThradPoolSampl:); boolW2K=fals; intMaxCount=10;//允许线程池中运行最多10个线程 //新建ManualRstEvnt对象并且初始化为无信号状态 ManualRstEvntvntX=nwManualRstEvnt(fals); Consol.WritLin(Quuing{0}itmstoThradPool,MaxCount); AlphaoAlpha=nwAlpha(MaxCount); //创建工作项 //注意初始化oAlpha对象的vntX属性 oAlpha.vntX=vntX; Consol.WritLin(QuutoThradPool0); try { //将工作项装入线程池 //这里要用到Windows以上版本才有的API,所以可能出现NotSupportExcption异常 ThradPool.QuuUsrWorkItm(nwWaitCallback(oAlpha.Bta),nwSomStat(0)); W2K=tru; } catch(NotSupportdExcption) { Consol.WritLin(ThsAPIsmayfailwhncalldonanon-Windowssystm.); W2K=fals; } if(W2K)//如果当前系统支持ThradPool的方法. { for(intiItm=1;iItmMaxCount;iItm++) { //插入队列元素 Consol.WritLin(QuutoThradPool{0},iItm); ThradPool.QuuUsrWorkItm(nwWaitCallback(oAlpha.Bta),nwSomStat(iItm)); } Consol.WritLin(WaitingforThradPooltodrain); //等待事件的完成,即线程调用ManualRstEvnt.St()方法 vntX.WaitOn(Timout.Infinit,tru); //WaitOn()方法使调用它的线程等待直到vntX.St()方法被调用 Consol.WritLin(ThradPoolhasbndraind(Evntfird)); Consol.WritLin(); Consol.WritLin(Loadacrossthrads); forach(objctoinoAlpha.HashCount.Kys) Consol.WritLin({0}{1},o,oAlpha.HashCount[o]); } Consol.RadLin(); rturn0; } } } } 程序中应该引起注意的地方: SomStat类是一个保存信息的数据结构,它在程序中作为参数被传递给每一个线程,因为你需要把一些有用的信息封装起来提供给线程,而这种方式是非常有效的。 程序出现的IntrLockd类也是专为多线程程序而存在的,它提供了一些有用的原子操作。 原子操作:就是在多线程程序中,如果这个线程调用这个操作修改一个变量,那么其他线程就不能修改这个变量了,这跟lock关键字在本质上是一样的。 我们应该彻底地分析上面的程序,把握住线程池的本质,理解它存在的意义是什么,这样才能得心应手地使用它。 白癜风最好的医院北京专业的白癜风医院
|