unity多线程操作

参考博客:http://blog.csdn.net/dingkun520wy/article/details/49181645

首先说明unity多线程操作的使用范围

(1) 大量耗时的数据计算
(2) 网络请求 
(3) 复杂密集的I/O操作
(4) Unity3D的NativePlugin中可以新建子线程。通过NativePlugin可以接入移动端iOS与Android中的成熟库,可以是Objective C, Java, C++三种语言交叉混合的方式组成NativePlugin,然后使用Android或者iOS的SDK开辟子线程。

总的来说

对于不是画面更新,也不是常规的逻辑更新(指包括AI、物理碰撞、角色控制这些),而是一些其他后台任务,则可以将这个独立出来开辟一个子线程。

基本关键字:

Start()开始;Abort()终止;Join()阻塞;Sleep()休眠;.
lock(obj){}保证数据一致

创建一个多线程

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;  
    }  
  
  
    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();  
            }  
        }  
    }  
  
}  

注意

确保线程的数据一致需要使用lock关键字,以免数据混乱。

单核线程速度是不如协同程序的。

因为多线程的转化次数要比协程高,若在多核当多核计算速率计算时间会倍率减少,而携程仍是单线程计算时间不变。

 

posted @ 2017-03-05 14:16  杨小行  阅读(10315)  评论(1编辑  收藏  举报