首页 新闻 赞助 找找看

一个多线程的问题

0
悬赏园豆:5 [已解决问题] 解决于 2009-11-27 09:22

 各位:  需求是这样的,   在Main方法里在. 我一次性要开10个线程, 十个线程跑同一个方法, 只是方法传入的参数不同,   等这十个线程都跑完了,  接下来再做Main方法里其他的事情

public void Main()

{

for(int i = 0 ; i<10 ;i++)

{

  thread td = new thred(方法名)    //   这里开始跑线程,

}

// DoSomeThing()                    //  一定要等到十个线程跑完了,再接下来处理下面的事.

}

 

上面这个程序只是一个比喻,  希望大家帮帮我,  当然最好有源码, 因为明天就要交差了.

不若相忘于江湖的主页 不若相忘于江湖 | 初学一级 | 园豆:51
提问于:2009-11-26 18:57
< >
分享
最佳答案
0

Code
//设置一个信号量用于同步
static System.Threading.Semaphore sema =
new System.Threading.Semaphore(0, 10);

static void ThreadProc(object state)
{
Console.WriteLine(state);
sema.Release();
}

static void Main(string[] args)
{

for (int i = 0; i < 10; i++)
{
//Run thread
System.Threading.Thread thread =
new System.Threading.Thread(ThreadProc);
thread.Start(i);
}

//Waitting
for (int i = 0; i < 10; i++)
{
sema.WaitOne();
}

Console.WriteLine(
"All threads done");

}

收获园豆:3
eaglet | 专家六级 |园豆:17139 | 2009-11-27 08:27
其他回答(2)
0
李占卫 | 园豆:238 (菜鸟二级) | 2009-11-26 19:43
0

    class Program

    {

        static int mMaxThread = 10;

        static int mCurTheads = 0;

        static AutoResetEvent mSet = new AutoResetEvent(false);

        static void Main(string[] args)

        {

            Console.WriteLine("press any key to start threads");

            Console.ReadKey();

            for (int i = 0; i < 10; i++)

            {

                Thread tmpThread = new Thread(T);

                tmpThread.Start(i);

            }

            mSet.WaitOne();

            Console.WriteLine("ok");

            Console.ReadKey();

        }

 

        static void T(object v)

        {

            Thread.Sleep(5000);

            mCurTheads++;

            Console.WriteLine("thread:"+v);

            if (mMaxThread == mCurTheads)

                mSet.Set();

        }

    }

收获园豆:2
Pvistely | 园豆:212 (菜鸟二级) | 2009-11-27 02:34
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册