2个线程的通讯问题 附上完整的代码,请大家帮忙,急!!~~
程序问题
程序入口同时开2个线程运行mMian(),在mMian()方法中再同时5个线程序运行subMain(),保证subMain运行完5次后,再开始下一次的mMian()循环。
小第用的vs2003 + .net1.1 的版本。
------------下面是模拟代码——————————
新建一个控制台应用程序,将下面代码复制后可以直接运行
using System;
using System.Threading;
namespace moreThread
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
private ManualResetEvent mainThread = new ManualResetEvent(false);
private ManualResetEvent subThread = new ManualResetEvent(false);
private int pCount = 0 ;
private void subMain()
{
lock (this)
{
Console.WriteLine( pCount.ToString());
if( this.pCount % 5 == 0)
subThread.Set();
Console.WriteLine( "运行结束:发送子信号 ");
}
}
private void mMian()
{
lock ( this )
{
int sCount = 0;
for ( int i=0; i <=20; i++ )
{
Thread sThread = new Thread( new ThreadStart( subMain ) );
sThread.Start();
Console.WriteLine( "子线程开始 ");
sCount++;
if(sCount > =5) //不能超过5个线程
{
sCount = 0; //
this.subThread.Reset();
Console.WriteLine( "等待子型号 ");
this.subThread.WaitOne(); //等待子信号
this.mainThread.Set(); //给主信号
}
}
}
}
static void Main(string[] args)
{
Class1 oClass = new Class1();
int sCount = 0;
for ( int w = 0; w <= 10 ; w++)
{
oClass.mainThread.Reset();
oClass.pCount = w;
Thread oThread = new Thread( new ThreadStart( oClass.mMian ) );
oThread.Start();
Console.WriteLine( "主线程开始: ");
sCount++;
if ( sCount == 2 ) //不能超过2个线程
{
sCount = 0;
Console.WriteLine( "等待 ");
oClass.mainThread.WaitOne();
Thread.Sleep(1000); //cpu
}
}
}
}
}
------解决方案--------------------看看我这个实现你的逻辑了没有,用WaitHandle.WaitAll,它可以让你等所有的线程都结束后再向下执行后边的代码, 比设置记数器好. 多个线程之间的公共记数器很难控制,而且加锁后效率低,失去多线程的优势了.
using System;
using System.Threading;
namespace moreThread
{
class SubMainClass
{
public ManualResetEvent SubMainFinished = new ManualResetEvent(false);
private int _mainThreadID = 0;
public SubMainClass(int mainThreadID)
{
_mainThreadID = mainThreadID;
}
public void subMain()
{
Co