zoukankan      html  css  js  c++  java
  • 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();
            }
             
        } 

  • 相关阅读:
    linux十九压缩解压
    linux第十八dd命令
    【51单片机】数据类型
    【博客园】
    【C++】简介与环境的搭建
    【树莓派】安装TeamViewer
    【树莓派】Makefile的编写
    【cJSON库】cJSON库的使用
    【树莓派】忘记系统用户密码,如何重置密码
    【树莓派】树莓派与PC机通信
  • 原文地址:https://www.cnblogs.com/lanyubaicl/p/11046222.html
Copyright © 2011-2022 走看看