版权声明:本文为博主 ( 黃彥霖 ) 原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38884324/article/details/80600303
功能如標題,沒甚麼能多說的,你們值接看代碼&結果就能理解了哈
延伸閱讀:本篇文章只是簡單範例,實際應用可以參考這篇
https://blog.csdn.net/weixin_38884324/article/details/80599967
C # :
using UnityEngine;
using System.Threading;
public class Test : MonoBehaviour
{
private void Start()
{
using (ManualResetEvent finish = new ManualResetEvent(false))
{
int currentThreadCount = 10; // 設定線程數量
for (int i = 0; i < 10; i++)
{
ThreadPool.QueueUserWorkItem((System.Object state) =>
{
print(state);
// 用原子的方式 將 currentThreadCount 的值遞減
// 因為如果用 currentThreadCount--; 會導致線程競爭,產生的結果為隨機。
if (Interlocked.Decrement(ref currentThreadCount) == 0)
{
// 如果"所有"線程都跑完,那就可以進行下一步啦
finish.Set();
}
}, "# " + i); // 請用這裡對線程傳值or傳資料,如果用全域變數傳會導致資料不同步
}
// 阻擋當前線程,除非收到 System.Threading.WaitHandle 信號
finish.WaitOne();
}
print("Finish !");
}
}
結果 :
可以發現 Finish ! 是最後才執行的。