C# 线程锁 Lock ,锁对象string字符串

string 字符锁

    class ThreadClass 
    {
        string str;
        string path;
        public ThreadClass(string str,string path)
        {
            this.str = str;
            this.path = path;
        }
        public void Thread01()
        {
            lock (str) {
                for (int i = 0; i < 10;i++ )
                {
                    Console.WriteLine(path+i);
                }
            }
        }
    }
    class Program
    {
        static string str01 = "name";
        static string str02 = "name";//这里锁对象是字符串会有不同效果
        static void Main(string[] args)
        {
            ThreadClass tc = new ThreadClass(str01,"这是线程1 ");
            Thread th1 = new Thread(new ThreadStart(tc.Thread01));
            th1.Start();
            //---------------------------------------------------------
            ThreadClass tc2 = new ThreadClass(str02, "这是线程2 ");
            Thread th2 = new Thread(new ThreadStart(tc2.Thread01));
            th2.Start();

            Console.ReadLine();
        }
         
    } 

 

 

 修改字符串执行效果不一样

    class Program
    {
        static string str01 = "name1";
        static string str02 = "name2";//这里锁对象是字符串会有不同效果
        static void Main(string[] args)
        {
            ThreadClass tc = new ThreadClass(str01,"这是线程1 ");
            Thread th1 = new Thread(new ThreadStart(tc.Thread01));
            th1.Start();
            //---------------------------------------------------------
            ThreadClass tc2 = new ThreadClass(str02, "这是线程2 ");
            Thread th2 = new Thread(new ThreadStart(tc2.Thread01));
            th2.Start();

            Console.ReadLine();
        }
         
    } 

 

posted @ 2019-06-18 17:00  蓝雨冰城  阅读(1076)  评论(0编辑  收藏  举报