线程图如上:
(两张图是引用)
协程(Coroutine)如下:
线程使CPU的性能得到了极大的提高,在写Unity的脚本时,刚好一个代码我想用Thread实现,但是在线程实现的时候,编译运行没有问题但是当执行线程的函数时,便开始报错,报错的提示是只要Find函数可以被调用。也就是说在Unity中线程只允许Thread调用组件。而在Unity中使用的是协程(Coroutine)。线程和协程的区别在于线程使用的CPU的时间片段和优先级的轮换,而协程一直占用,不采用cpu的轮换机制。
在我看来Unity的协程和线程是差不多的
yield相当于中断向量,将CPU控制权让出。
这个程序的运行过程是这样的:using UnityEngine; using System.Collections; public class example : MonoBehaviour { IEnumerator Do() { print("Do now"); yield return new WaitForSeconds(2); print("Do 2 seconds later"); } IEnumerator Awake() { yield return StartCoroutine("Do"); print("Also after 2 seconds"); print("This is after the Do coroutine has finished execution"); } }
这个例子将执行Do,并等待,直到Do完成再执行其他语句.