在Main方法里在. 我一次性要开10个线程, 十个线程跑同一个方法, 但方法传入的参数不同, 等这十个线程都跑完了, 接下来再做Main方法里其他的事情
转载的:
我有个想法
设定一个变量t,当新建一个线程时t+1,线程完成时t-1,
线程完成时调用一个委托,
在委托方法中通过判断t是否等于0来确定所有线程是否执行完毕
在main中通过do while t <> 0来判断也可以……
这是第二种方法. 但没有测试过.
代码
using
System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections.ObjectModel;
namespace ThreadControler
{
class Program
{
static void Main( string [] args)
{
m_ResultInfoList = new Collection < string > ();
Collection < Thread > threadList = new Collection < Thread > ();
for ( int i = 0 ; i < 10 ; i ++ )
{
Thread workThread = new Thread( new ParameterizedThreadStart(TestThreadProc));
threadList.Add(workThread);
workThread.Start(i);
}
m_ThreadReadyEvent.Set();
foreach (Thread tempThread in threadList)
{
tempThread.Join();
}
foreach (String tempResult in m_ResultInfoList)
{
Console.WriteLine(tempResult);
}
Thread.Sleep( 5000 );
}
private static Mutex m_ResultListMutex = new Mutex();
private static Collection < String > m_ResultInfoList = null ;
private static EventWaitHandle m_ThreadReadyEvent = new EventWaitHandle( false , EventResetMode.ManualReset);
private static void TestThreadProc(Object index)
{
m_ThreadReadyEvent.WaitOne();
for ( int i = 0 ; i < 5 ; i ++ )
{
Thread.Sleep( 500 );
}
m_ResultListMutex.WaitOne();
m_ResultInfoList.Add(index.ToString());
m_ResultListMutex.ReleaseMutex();
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections.ObjectModel;
namespace ThreadControler
{
class Program
{
static void Main( string [] args)
{
m_ResultInfoList = new Collection < string > ();
Collection < Thread > threadList = new Collection < Thread > ();
for ( int i = 0 ; i < 10 ; i ++ )
{
Thread workThread = new Thread( new ParameterizedThreadStart(TestThreadProc));
threadList.Add(workThread);
workThread.Start(i);
}
m_ThreadReadyEvent.Set();
foreach (Thread tempThread in threadList)
{
tempThread.Join();
}
foreach (String tempResult in m_ResultInfoList)
{
Console.WriteLine(tempResult);
}
Thread.Sleep( 5000 );
}
private static Mutex m_ResultListMutex = new Mutex();
private static Collection < String > m_ResultInfoList = null ;
private static EventWaitHandle m_ThreadReadyEvent = new EventWaitHandle( false , EventResetMode.ManualReset);
private static void TestThreadProc(Object index)
{
m_ThreadReadyEvent.WaitOne();
for ( int i = 0 ; i < 5 ; i ++ )
{
Thread.Sleep( 500 );
}
m_ResultListMutex.WaitOne();
m_ResultInfoList.Add(index.ToString());
m_ResultListMutex.ReleaseMutex();
}
}
}
下面这个测试过. 可以用.
代码
//
设置一个信号量用于同步 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"); }