(一)多線程的建立c#
Thread t = new Thread(new ThreadStart(Go));
多線程
Thread t1 = new Thread(Go);學習
兩種建立方式沒有區別;測試
(二)多線程的狀態控制和優先級
spa
多線程有4種狀態:Start()開始;Abort()終止;Join()阻塞;Sleep()休眠;線程
有5種優先級:從高到底依次爲:Highest,AboveNormal ,Normal ,BelowNormal ,Lowest;code
線程的默認優先級爲Normal;orm
多線程實例
遊戲
/* * * 遊戲多線程 * */ 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; //**/ ///*測試線程鎖 /*/ Thread th1 = new Thread(new ThreadStart(Th_lockTest)); th1.Name = "test1"; th1.Start(); Thread th2 = new Thread(new ThreadStart(Th_lockTest)); th2.Name = "test2"; th2.Start(); //*/ } 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(); } } } }