一、关于c#多线程的使用
在实例化Thread的实例时,需要提供一个委托,在实例化这个委托时所用到的参数是线程将来启动时要运行的方法,在.net中提供了两种启动线程的方式,一种为带参启动,一种为不带参启动。
1、不带参数的启动方式
使用ThreadStart委托启动线程。
using UnityEngine;
using System.Collections;
using System.Threading;
using System;
public class ThreadOne : MonoBehaviour {
void Start ()
{
InVokeThreadOne();
}
void InVokeThreadOne()
{
Thread _trdOne = new Thread(new ThreadStart(MethodOne));
_trdOne.Name = "threadOne";
_trdOne.Start();
}
void MethodOne()
{
for(int i = 0 ;i<10;i++)
{
print(DateTime.Now);
Thread.Sleep(1000);
}
}
}
2、带参数的启动方式
使用ParameterizedThreadStart委托来启动线程。
using UnityEngine;
using System.Collections;
using System.Threading;
using System;
public class ThreadOne : MonoBehaviour {
void Start ()
{
InVokeThreadTwo();
InVokeThreadThree();
InVokeThreadFour();
}
void InVokeThreadTwo()
{
Thread _trdTwo = new Thread(new ParameterizedThreadStart(MethodTwo));
_trdTwo.Name = "treadTwo";
_trdTwo.Start(2000);
}
void InVokeThreadThree()
{
Thread _trdThree = new Thread(new ParameterizedThreadStart(MethodThree));
_trdThree.Name = "treadThree";
_trdThree.Start(new ThreadParams(1000,10));
}
void InVokeThreadFour()
{
ThreadParamsTwo _cTrdParms = new ThreadParamsTwo(1000,10);
_cTrdParms.Start();
}
void MethodTwo( object m_iSleepTime)
{
int m_iTime = int.Parse(m_iSleepTime.ToString());
for(int i = 0 ;i<10;i++)
{
print(DateTime.Now);
Thread.Sleep(m_iTime);
}
}
void MethodThree( object m_cThreadParm)
{
ThreadParams m_cTParm = (ThreadParams) m_cThreadParm;
for(int i = 0 ;i<m_cTParm.LoopCount;i++)
{
print(DateTime.Now);
Thread.Sleep(m_cTParm.SleepTime);
}
}
class ThreadParams
{
private int _iSleepTime;
private int _iLoopCount;
public int SleepTime
{
get
{
return _iSleepTime;
}
}
public int LoopCount
{
get
{
return _iLoopCount;
}
}
public ThreadParams( int m_iSleepTime,int m_iLoopCount)
{
_iSleepTime = m_iSleepTime;
_iLoopCount = m_iLoopCount;
}
}
class ThreadParamsTwo
{
private int _iSleepTime;
private int _iLoopCount;
private Thread _trdFour;
public int SleepTime
{
get
{
return _iSleepTime;
}
}
public int LoopCount
{
get
{
return _iLoopCount;
}
}
public ThreadParamsTwo( int m_iSleepTime,int m_iLoopCount)
{
_iSleepTime = m_iSleepTime;
_iLoopCount = m_iLoopCount;
_trdFour = new Thread(new ThreadStart(ThreadRun));
}
void ThreadRun()
{
for(int i = 0 ;i< _iLoopCount;i++)
{
print(DateTime.Now);
Thread.Sleep(_iSleepTime);
}
}
public void Start()
{
_trdFour.Start();
}
}
}
二、多线程常用函数
启动线程Start
挂起线程Suspend
休眠线程Sleep
恢复挂起Resume
终止线程Abord
等待线程中止Join