• C#多线程(浅谈线程安全)


    先撸一段代码,再说

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    
    namespace ThreadTest0902
    {
        public class Program
        {
            bool bl = false;
            static void Main(string[] args)
            {
                Program p = new Program();
                Thread thread = new Thread(p.Print);
                thread.Start();
    
                p.Print();
                Console.ReadKey();
    
            }
            public void Print()
            {
                    if (!bl)
                    {
                        Console.WriteLine("I'm False");
                        bl = true;
                    }
            }
        }
    }
    

    执行后你会发现,有时候打印一次,有时候会打印两次

    其实大家也能猜到是什么原因了,在第一个线程打印时,bl还是false,另一个线程进判断语句了,于是也进来打印了

    为了避免这样无法预知的结果,于是我们就想着,在第一个线程(线程A)进行操作上,把门关上,锁起来,另一个线程(线程B)只能在外面等着,等线程A处理好了,出去了,才可以让线程B进来

    于是微软爸爸就给了我们把万能锁(lock)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    
    namespace ThreadTest0902
    {
        public class Program
        {
            bool bl = false;
            static readonly object locker = new object();
            static void Main(string[] args)
            {
                Program p = new Program();
                Thread thread = new Thread(p.Print);
                thread.Start();
    
                p.Print();
                Console.ReadKey();
    
            }
            public void Print()
            {
                lock (locker)
                {
                    if (!bl)
                    {
                        Console.WriteLine("I'm False");
                        bl = true;
                    }
                }
            }
        }
    }
    

    单独把这个拿出来说下

    static object locker = new object();

    一开始我只是写成object locker = new object();

    后来看了网上的代码,看了下,基本上都是private static readonly于是我就客串下百度

    private:如果该实例是public,那么无关的代码也可能会锁定该对象,那就会出现多个线程等待同一个对象释放,导致死锁

    static:同上,如果是公共数据类型也会出现上述问题

    readonly:一旦在lock中对象值变了,那么其他线程就可以进来执行了,因为互斥锁的对象变了

    菜鸟宝哥持续更新中...

  • 相关阅读:
    丑数(摘)
    queue 之团队队列(摘)
    stack 集合栈计算机 (摘)
    反片语(map)
    stl的集合set——安迪的第一个字典(摘)
    stringstream函数(i o)
    T
    S
    R
    java面试题
  • 原文地址:https://www.cnblogs.com/gothic/p/5833664.html
Copyright © 2020-2023  润新知