Unity中使用多线程

说明

  • unity c#使用多线程需要注意的点在注释中
  • 本文做的事
    • 开启线程
    • 共享变量
    • 结束线程

代码和注释

using System.Collections;
using System.Collections.Generic;
using System.Threading;

using UnityEngine;

/*
c# 多线程
  可以执行非mono代码
  可以使用基本类型和struct

  不能执行 mono代码

#多线程使用模板
新建线程,设置启动参数,启动方法,开始执行,等待结果

#多线程操作
锁定变量
休眠
结束

#线程池

知识点
  1、当在主线程中创建了一个线程,那么该线程的IsBackground默认是设置为FALSE的。

  2、当主线程退出的时候,IsBackground=FALSE的线程还会继续执行下去,直到线程执行结束。

  3、只有IsBackground=TRUE的线程才会随着主线程的退出而退出
 */

namespace DC
{

  public class SimpleMultiThread : MonoBehaviour
  {
    Thread thread;

    int sharedValue;
    object sharedValueLock = new object();

    void Start()
    {
      Debug.Log(Thread.CurrentThread.Name);
      Debug.Log(Thread.CurrentThread.ManagedThreadId.ToString());
      Debug.Log(Thread.CurrentThread.ToString());
      SimpleUse();
      StartCoroutine(TestAbort());
      Debug.Log(sharedValue);
    }

    void WorkFunction()
    {
      Debug.Log("WorkFunction run 1");
      Debug.Log(Thread.CurrentThread.Name);
      Debug.Log(Thread.CurrentThread.ManagedThreadId.ToString());
      Debug.Log(Thread.CurrentThread.ToString());
      Thread.Sleep(1);
      Debug.Log("WorkFunction run 2");
      lock(sharedValueLock)
      {
        sharedValue = 10;
      }
      while (true)
      {
        //这样无法abort
        //pc上,因为无法abort,前台线程都结束后这个线程即使 IsBackground = true也没有停止
        // for(var i = 0; i < 10000000; i++){
        //   var value = Mathf.Sin(Mathf.Pow(2,16));
        // }
        //这样可以abort
        /*
        小结
        正在运行的线程不能停止,除非杀死进程
        如果一个线程正在进行大规模密集运算,在循环中判断是否需要停止,让线程主动结束
         */
        Thread.Sleep(1000);
        Debug.Log("round");
      }
    }

    void WorkFunction(object val)
    {
      Debug.Log("WorkFunction run " + val.ToString());
      lock(sharedValueLock)
      {
        sharedValue = (int)(val);
        // sharedValue = int.Parse(val.ToString());
      }
    }

    public void SimpleUse()
    {
      thread = new Thread(new ThreadStart(WorkFunction));
      thread.Name = "worker";
      thread.IsBackground = true;
      thread.Start();
      // thread = new Thread(new ParameterizedThreadStart(WorkFunction));
      // thread.Name = "worker-param";
      // thread.IsBackground = true;
      // thread.Start(3);
    }

    public IEnumerator TestAbort()
    {
      yield return new WaitForSeconds(6);
      thread.Abort();
      Debug.Log("Abort");
    }

  }

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值