c#之lock和单例模式

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 ();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值