Unity多线程使用(线程池)
1.在C#中使用线程池需要以下这个类库using System.Threading
2.开单个线程(unity程序停止前 线程一定要关闭)
private Thread tempThread; void Start () { tempThread = new Thread(MyThread);//将方法注册到线程句柄当中,注意保留这个句柄,最后需要关闭线程,要不然会造成unity停止运行线程不停止。 tempThread.Start();//开启线程。 } //这是线程方法 private void MyThread() { Debug.Log("开了线程"); }
关闭线程(Thread.Abort();)
3.线程池的使用
线程池相对于线程而言更加方便,在线程池中的线程是由系统进行统一管理,我们在使用的过程中不需要自己去对线程进行开关操作,这些系统都会给我们做了。而且线程池还有一个好处,就是可以传参!
private int m_iParam;//随便一个类型的参数 void Start () { ThreadPool.QueueUserWorkItem(new WaitCallback(MyThread), m_iParam);//将方法添加进线程池,并传入参数 } private void MyThread(object param) { Debug.Log("开了线程"); }
也可以封装成方法
//线程池上的队列 public static void QueueOnThreadPool(WaitCallback callBack, object state = null) { ThreadPool.QueueUserWorkItem(callBack, state); }
c#脚本
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Threading; using System; public class XianCheng : MonoBehaviour { public static XianCheng Current; static Thread mainthread; //主线程 private List<Action> actions = new List<Action>(); // public int[]tssd=new int [30]; public bool bol = false; public static bool IsMainThread() { return Thread.CurrentThread == mainthread; } private void Awake() { Current = this; mainthread = Thread.CurrentThread; bol = true; } private void OnDestroy() { mainthread.Abort(); bol = false; } void Start() { QueueOnThreadPool((Func_0), 0); }
void Update() { var currentActions = new List<Action>(); lock (actions) { currentActions.AddRange(actions); foreach (var item in currentActions) actions.Remove(item); } } //主线程上的队列 public static void QueueOnMainThread(Action action) { if (IsMainThread()) { action(); return; } lock (Current.actions) { Current.actions.Add(action); } } //线程池上的队列 public static void QueueOnThreadPool(WaitCallback callBack, object state = null) { ThreadPool.QueueUserWorkItem(callBack, state); } }
void Func_0(object parm) { try { while (bol) { tssd[0] += 1; Thread.Sleep(100); } } catch (Exception e) { Debug.Log(e.Message); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南