Unity3d多线程
2015-10-16 18:01
465 查看
(一)多线程的创建
Thread t = new Thread(new ThreadStart(Go));
Thread t1 = new Thread(Go);
两种创建方式没有区别;
(二)多线程的状态控制和优先级
多线程有4种状态:Start()开始;Abort()终止;Join()阻塞;Sleep()休眠;
有5种优先级:从高到底依次为:Highest,AboveNormal
,Normal ,BelowNormal ,Lowest;
线程的默认优先级为Normal;
多线程实例
注意:
1,当多个线程同时访问同一数据时要加线程锁lock。
Object n=new Object();
long shu = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
lock (n)
{
xian = 1;
}
}
Thread t = new Thread(new ThreadStart(Go));
Thread t1 = new Thread(Go);
两种创建方式没有区别;
(二)多线程的状态控制和优先级
多线程有4种状态:Start()开始;Abort()终止;Join()阻塞;Sleep()休眠;
有5种优先级:从高到底依次为:Highest,AboveNormal
,Normal ,BelowNormal ,Lowest;
线程的默认优先级为Normal;
多线程实例
/* * * 游戏多线程 * */ using UnityEngine; using System.Threading; public class BaseThread{ private static BaseThread instance; object obj = new object(); int num = 0; private BaseThread() { /*测试线程优先级 /*/ Thread th1 = new Thread(Th_test1); //创建一个线程 Thread th2 = new Thread(Th_test2); Thread th3 = new Thread(Th_test3); th1.Start(); th2.Start(); th3.Start(); //学习优先级 th1.Priority = System.Threading.ThreadPriority.Highest; //优先级最高 th2.Priority = System.Threading.ThreadPriority.Normal; th3.Priority = System.Threading.ThreadPriority.Lowest; //**/ ///*测试线程锁 /*/ Thread th1 = new Thread(new ThreadStart(Th_lockTest)); th1.Name = "test1"; th1.Start(); Thread th2 = new Thread(new ThreadStart(Th_lockTest)); th2.Name = "test2"; th2.Start(); //*/ } public static BaseThread GetInstance() { if (instance == null) { instance = new BaseThread(); } return instance; } //测试多线程锁 public void Th_lockTest() { Debug.Log("测试多线程"); while (true) { lock (obj) { //线程“锁” num++; Debug.Log(Thread.CurrentThread.Name + "测试多线程" + num); } Thread.Sleep(100); if (num > 300) { Thread.CurrentThread.Abort(); } } } //测试多线程优先级 public void Th_test1() { for (int i = 0; i < 500; i++) { Debug.Log("测试多线程1执行的次数:" + i); if(i >200) { Thread.CurrentThread.Abort(); } } } public void Th_test2() { for (int i = 0; i < 500; i++) { Debug.Log("测试多线程2执行的次数:" + i); if (i > 300) { Thread.CurrentThread.Abort(); } } } public void Th_test3() { for (int i = 0; i < 500; i++) { Debug.Log("测试多线程3执行的次数:" + i); if (i > 400) { Thread.CurrentThread.Abort(); } } } }
注意:
1,当多个线程同时访问同一数据时要加线程锁lock。
Object n=new Object();
long shu = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
lock (n)
{
xian = 1;
}
}
相关文章推荐
- Python3写爬虫(四)多线程实现数据爬取
- Kinect结合Unity3D引擎开发体感游戏(一)
- c#调用COM组件
- C#实现把指定数据写入串口
- C#动态创建button的方法
- C#中抽象方法与虚拟方法的区别
- c#中虚函数的相关使用方法
- C#使用加边法计算行列式的值
- C#实现多线程的同步方法实例分析
- C#中尾递归的使用、优化及编译器优化
- C#实现子窗体与父窗体通信方法实例总结
- C#通用邮件发送类分享
- C#中this的用法集锦
- C#.NET获取拨号连接的宽带连接方法
- C#异步绑定数据实现方法
- C#实现AddRange为数组添加多个元素的方法
- C#中Equality和Identity浅析
- C#生成饼形图及添加文字说明实例代码
- linux网络编程----->高并发--->多线程并发服务器