using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
public class duoxian : MonoBehaviour {
// Use this for initialization
bool m_sbstart=false;
void Start () {
m_sbstart=true;//开启线程
Thread tha = new Thread(RunTread);
tha.Start();
}
void RunTread()
{
while(m_sbstart)
{
print("yes");
}
}
void onApplicationQuit()
{
m_sbstart=false;//关闭线程,避免资源泄漏或崩溃
}
}
多线程需要注意的是什么?
1,加锁,为什么要加锁,意思就是当有多个线程对物体进行同时的读写时,如果不进行加锁,就会出现数据混乱。 2,死锁,既然加了锁,就要避免死锁,死锁有四个必要条件,只要出现死锁,必定是因为这四种的其中一种引起的。
(1) 互斥条件:一个资源每次只能被一个进程使用。
(2) 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。
(3) 不剥夺条件:进程已获得的资源,在末使用完之前,不能强行剥夺。
(4) 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。
如何加锁?
// Use this for initialization
int thecount = 300;
bool m_sbstart;
public static object c = new object();
void Start()
{
m_sbstart = true;
Thread the1 = new Thread(therun1);
Thread the2 = new Thread(therun2);
the1.Start();
the2.Start();
}
void therun1()
{
for (int i = 1; i < 10; i++)
{
lock (c)
{
thecount += 1;
Debug.Log(thecount);
}
}
}
void therun2()
{
for (int i = 1; i < 10; i++)
{
lock (c)
{
thecount += 100;
Debug.Log(thecount);
}
}
}