、
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour {
public Thread th;
public Thread th2;
// Use this for initialization
void Start()
{
th = new Thread(revData);
//th.Priority = System.Threading.ThreadPriority.Normal;
th.IsBackground = true;
th.Start();
//
th2 = new Thread(revData2);
//th.Priority = System.Threading.ThreadPriority.Normal;
th2.IsBackground = true;
th2.Start();
}
public int count = 0;
private void revData()
{
while (
Thread.CurrentThread.ThreadState != (ThreadState.Background | ThreadState.AbortRequested)
)
{
count++;
Debug.Log("revData:");// + count.ToString());
//Thread.Sleep(1);
Thread.SpinWait(1);
}
}
private void revData2()
{
while (true)
{
count++;
Debug.Log("revData2:");// + count.ToString());
//Find can only be called from the main thread.
//GameObject c = GameObject.Find("Cube");
Thread.Sleep(1000);
}
}
// Update is called once per frame
void Update () {
}
private void OnApplicationPause(bool pause)
{
if (null != th2)
{
if(th2.IsAlive)
{
th2.Interrupt();
}
}
}
private void OnApplicationQuit()
{
th.Abort();
th2.Abort();
}
}
Thread.Sleep虽是静态方法,但指的是当前线程
另外由于线程 睡眠/唤醒 需要时间
Thread.SpinWait反应速度度更快一些
我有必要 警告一下: Thread.SpinWait(10); //自旋10毫秒,性能会极差, CPU 会被占满
我这边有一个需求,不想使用 内置 Timer —— 所以需要线程休眠。
每隔10毫秒执行一次。
do{
Thread.SpinWait(10); //自旋10毫秒
Thread.Sleep(10); //休眠10毫秒
}while(true);
结果:Thread.SpinWait(10); CPU被占满 100% —— “自旋” (这个词的意思 或许就是说:没事做的时候,也要折腾一点事儿出来)。
——————————————————————
当然:
Thread.SpinWait(10); 精度准一点(没有线程的 唤醒时间,休眠10ms,实际休眠 10.001 ms)
Thread.Sleep(10); 精度差一点(有线程的 唤醒时间,休眠10ms,实际休眠 10.1 ms)
MSDN解释: SpinWait 方法在实现锁定方面十分有用。.NET Framework 中的类(例如 Monitor 和 ReaderWriterLock)在内部使用此方法。SpinWait 实质上会将处理器置于十分紧密的循环中,其循环计数由 iterations 参数指定。因此,等待的持续时间取决于处理器的速度。 针对这一点,将此方法与 Sleep 方法进行对比。调用 Sleep 的线程会产生其处理器时间当前片断的剩余部分,即使指定的时间间隔为零也不例外。如果为 Sleep 指定非零的时间间隔,则线程计划程序会不考虑该线程,直到该时间间隔结束。
值得注意的是SpinWait只有在SMP或多核CPU下才具有使用意义。在单处理器下,旋转非常浪费CPU时间,没有任何意义。