• 同步锁


     class Program
        {
            static void Main(string[] args)
            {
                //控制台默认输出行数是300,可以设置
                Console.BufferHeight = 1000;
    
                TicketSeller t1 = new TicketSeller("A");
                TicketSeller t2 = new TicketSeller("B");
               
                Console.ReadLine();
            }
    
        }
    
    
        public class TicketSeller
        {
            public static int count = 500;
            public static object locker = new object();
    
            public TicketSeller(string name)
            {
                Console.WriteLine(count);
                Thread th = new Thread(Sell);
                th.Name = name;
                th.IsBackground = true;
                th.Start();
                Console.WriteLine(count);
            }
    
            public void Sell()
            {
    
                while (count > 0)
                {
                    //引用类型对象在内存中分配的对象头空间(栈空间)最后2bit存放锁标识;lock只要是静态变量就可以,this.GetType()
                    lock (locker)
                    {
                        TicketSeller.count--;
                        Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "剩余{0}", count);
                    }
    
                }
            }
        }
    或者使用Monitor

    bool isGetLocker = false;
                    try
                    {
                        //引用类型对象在内存中分配的对象头空间(栈空间)最后2bit存放锁标识
                        Monitor.Enter(locker, ref isGetLocker);
                        TicketSeller.count--;
                        Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "剩余{0}", count);
    
                    }
                    catch (Exception e)
                    {
    
                        throw e;
                    }
                    finally
                    {
                        if (isGetLocker)
                        {
                            Monitor.Exit(locker);
                        }
                    }
    或者给方法标记特性
     [MethodImpl(MethodImplOptions.Synchronized)]

    线程安全单例模式
      class SingleTest
        {
            private static SingleTest s = null;
            private SingleTest() { }
    
            static SingleTest GetSingle()
            {
                //this,type
                lock (typeof(SingleTest))
                {
                    if (s == null)
                    { s = new SingleTest(); }
                }
                return s;
    
            }
        }


  • 相关阅读:
    eclipse maven 插件 安装 和 配置
    Windows下 maven3.0.4的安装步骤+maven配置本地仓库
    js中转换Date日期格式
    Java 集合类详解
    java的反射机制
    Java 单例模式详解
    Http协议与TCP协议简单理解
    初识JavaScript,Ajax,jQuery,并比较三者关系
    MyBatis
    MyEclipse、Eclipse优化设置
  • 原文地址:https://www.cnblogs.com/tgdjw/p/4602076.html
Copyright © 2020-2023  润新知