參考博客: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關鍵字,以免數據混亂。
單核線程速度是不如協同程序的。
因為多線程的轉化次數要比協程高,若在多核當多核計算速率計算時間會倍率減少,而攜程仍是單線程計算時間不變。