c#之lock和单例模式

时间:2022-01-13 18:19:35
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;

public class SingleModle {

//单例模式
private static SingleModle _singleModle;

private SingleModle() //私有化构造函数,外界无法通过new来实例化该类
{

}

public static SingleModle GetInstance()
{
if (_singleModle == null)
{
_singleModle = new SingleModle ();
}
return _singleModle;
}

public string name = "Likang";
private int level = 6;
private static readonly object obj = new object ();

public Thread threadone;
public Thread threadtwo;

public Queue<int> _queue = new Queue<int>();

public void startThread()
{
threadone = new Thread (SS);
//threadone.IsBackground = true; //将其变成后台线程
threadone.Start ();

threadtwo = new Thread (SS);
// threadtwo.IsBackground = true;
threadtwo.Start ();
}

public void SS()
{
//lock关键字可以用来确保代码块完成运行,而不被其他线程中断;应避免锁定public类型,否则实例将超出
//代码的控制范围,常见的结构lock(this),lock(typeof(MyType)),lock("a")违反此准则

//lock必需要所定引用类型,reference type ,如果是值累型,則编译不会通过的,string类型非常危险,可能造成锁死
lock (_queue) //lock来所定queue,一个先程志行完后另一先程才能执行
{
_queue.Enqueue (5);

Thread.Sleep (5000);//5000毫秒
}

}


}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FileWriteAndRead : MonoBehaviour {
private BoxCollider[] cube;

// Use this for initialization
void Start ()
{
//GameObject.FindObjectOfType<S>() 找到hierarchy中第一个有S组件的游戏对象
// cube = GameObject.FindObjectsOfType<BoxCollider> (); //找到hierarchy中有此组件的所有游戏对象
// foreach (var item in cube)
// {
// print (item.name);
// }
//
// //SingleModle ss = new SingleModle ();
// print (SingleModle.GetInstance().name);

SingleModle.GetInstance ().startThread ();

}

// Update is called once per frame
void Update ()
{
//lock锁住則先打印1,5秒之后打印2;没有lock則是2
print (SingleModle.GetInstance()._queue.Count);
}

void OnApplicationQuit()
{
SingleModle.GetInstance().threadone.Abort();
SingleModle.GetInstance ().threadtwo.Abort ();
}
}