Unity3d多线程

时间:2023-03-09 00:51:13
Unity3d多线程

http://blog.****.net/dingkun520wy/article/details/49181645

(一)多线程的创建

Thread t = new Thread(new ThreadStart(Go));

Thread t1 = new Thread(Go);

两种创建方式没有区别;

(二)多线程的状态控制和优先级

多线程有4种状态:Start()开始;Abort()终止;Join()阻塞;Sleep()休眠;

有5种优先级:从高到底依次为:Highest,AboveNormal ,Normal ,BelowNormal ,Lowest;

线程的默认优先级为Normal;

多线程实例

  1. /*
  2. *
  3. * 游戏多线程
  4. * */
  5. using UnityEngine;
  6. using System.Threading;
  7. public class BaseThread{
  8. private static BaseThread instance;
  9. object obj = new object();
  10. int num = 0;
  11. private BaseThread()
  12. {
  13. /*测试线程优先级
  14. /*/
  15. Thread th1 = new Thread(Th_test1);              //创建一个线程
  16. Thread th2 = new Thread(Th_test2);
  17. Thread th3 = new Thread(Th_test3);
  18. th1.Start();
  19. th2.Start();
  20. th3.Start();
  21. //学习优先级
  22. th1.Priority = System.Threading.ThreadPriority.Highest;         //优先级最高
  23. th2.Priority = System.Threading.ThreadPriority.Normal;
  24. th3.Priority = System.Threading.ThreadPriority.Lowest;
  25. //**/
  26. ///*测试线程锁
  27. /*/
  28. Thread th1 = new Thread(new ThreadStart(Th_lockTest));
  29. th1.Name = "test1";
  30. th1.Start();
  31. Thread th2 = new Thread(new ThreadStart(Th_lockTest));
  32. th2.Name = "test2";
  33. th2.Start();
  34. //*/
  35. }
  36. public static BaseThread GetInstance()
  37. {
  38. if (instance == null)
  39. {
  40. instance = new BaseThread();
  41. }
  42. return instance;
  43. }
  44. //测试多线程锁
  45. public void Th_lockTest()
  46. {
  47. Debug.Log("测试多线程");
  48. while (true)
  49. {
  50. lock (obj)
  51. {                                //线程“锁”
  52. num++;
  53. Debug.Log(Thread.CurrentThread.Name + "测试多线程" + num);
  54. }
  55. Thread.Sleep(100);
  56. if (num > 300)
  57. {
  58. Thread.CurrentThread.Abort();
  59. }
  60. }
  61. }
  62. //测试多线程优先级
  63. public void Th_test1()
  64. {
  65. for (int i = 0; i < 500; i++)
  66. {
  67. Debug.Log("测试多线程1执行的次数:" + i);
  68. if(i >200)
  69. {
  70. Thread.CurrentThread.Abort();
  71. }
  72. }
  73. }
  74. public void Th_test2()
  75. {
  76. for (int i = 0; i < 500; i++)
  77. {
  78. Debug.Log("测试多线程2执行的次数:" + i);
  79. if (i > 300)
  80. {
  81. Thread.CurrentThread.Abort();
  82. }
  83. }
  84. }
  85. public void Th_test3()
  86. {
  87. for (int i = 0; i < 500; i++)
  88. {
  89. Debug.Log("测试多线程3执行的次数:" + i);
  90. if (i > 400)
  91. {
  92. Thread.CurrentThread.Abort();
  93. }
  94. }
  95. }
  96. }

注意:

1,当多个线程同时访问同一数据时要加线程锁lock。

    1. Object n=new Object();
    2. long shu = 0;
    3. // Use this for initialization
    4. void Start () {
    5. }
    6. // Update is called once per frame
    7. void Update ()
    8. {
    9. lock (n)
    10. {
    11. xian = 1;
    12. }
    13. }