https://mp.csdn.net/postedit/80261275
今天去面試..面試官竟然說(shuō)子線程的Action不能發(fā)送到主線程執(zhí)行... ...廢話不說(shuō)上干貨
using?System.Collections;
using?System.Collections.Generic;
using?UnityEngine;
using?System;
using?System.Threading;
public?class?ActionDemo?:?MonoBehaviour?{
????public?static?List>?actionlist?=?new?List>();
????void?Start()
????{
????????actionlist.Add(?curname?=>?{
????????????Debug.Log?("action1?:"?+?curname);
????????});
????????actionlist.Add(?curname?=>?{
????????????Debug.Log?("action2?:"?+?curname);
????????});
????????//開啟子線程
????????Thread?th?=?new?Thread(ThreadChild);
????????th.Start();
????}
????static?void?ThreadChild()
????{
????????//循環(huán)三次?關(guān)閉線程,養(yǎng)成良好習(xí)慣
????????for?(int?i?=?0;?i?<?3;?i++)?{
????????????//鎖住保證線程安全
????????????lock(actionlist){
????????????????actionlist.Add(?curname?=>?{
????????????????????//這里填子線程中?想去主線程調(diào)用的代碼?,例如改變UI
????????????????????Debug.Log?("ThreadChild?:"?+?curname);
????????????????});
????????????????Thread.Sleep(1000);
????????????}
????????}
????}
????void?Update(){
????????//遍歷action?在Update中調(diào)用action自然是主線程調(diào)用
????????for?(int?i?=?0;?i?<?actionlist.Count;?i++)?{
????????????ActionDemo.actionlist?[i]?(Time.time+"");
????????}
????????actionlist.Clear();
????}
}