zoukankan      html  css  js  c++  java
  • 多线程 对变量共享和独享的验证 Anny

    在上一篇介绍多线程的基本知识中有一段代码,通过略微修改并运行,理解了多线程对变量的共享和独享。

    namespace MultiThread
    {
        class SynchronizationThreadsExample
        {
            private int counter = 0;  //成员变量被多个线程共享
            static void Main(string[] args)
            {
                SynchronizationThreadsExample STE = new SynchronizationThreadsExample();
                STE.ThreadFunction();
                Console.ReadLine();
            }
            public void ThreadFunction()
            {
                Thread DummyThread = new Thread(new ThreadStart(SomeFunction));
                DummyThread.IsBackground = true;
                DummyThread.Name = "First Thread";
                DummyThread.Start();
                Console.WriteLine("Started thread {0}", DummyThread.Name);
                Thread DummyPriorityThread = new Thread(new ThreadStart(SomeFunction));
                DummyPriorityThread.IsBackground = true;
                DummyPriorityThread.Name = "Second Thread";
                DummyPriorityThread.Start();
                Console.WriteLine("Started thread {0}", DummyPriorityThread.Name);
                DummyThread.Join();
                DummyPriorityThread.Join();
            }
            public void SomeFunction()
            {
                try
                {
                    while (counter < 10)
                    {
                        int tempCounter = counter;  //tempCounter 被当前线程独享
                        tempCounter++;
                        Console.WriteLine("Thread . SomeFunction-tempCounter: " + Thread.CurrentThread.Name + tempCounter);
                        Console.WriteLine("*************");
                        Thread.Sleep(1000); //时间设成1000ms,可以很好的看出两个线程的交替运行
                        counter = tempCounter;
                        Console.WriteLine("Thread . SomeFunction-counter: " + Thread.CurrentThread.Name + counter);
                    }
                }
                catch (ThreadInterruptedException Ex)
                {
                    Console.WriteLine("Exception in thread " + Thread.CurrentThread.Name);
                }
                finally
                {
                    Console.WriteLine("Thread Exiting. " + Thread.CurrentThread.Name);
                }
            }
        }
    }

    小结:类的成员变量被多个线程共享;类中成员函数的局部变量被单个当前线程独享。

  • 相关阅读:
    Oracle之表空间
    Oracle 数据库实现数据更新:update、merge
    union和union all用法
    SQL Server 使用游标更新数据库中的数据(使用存储过程)
    MDX函数(官方顺序,带示例)
    开窗函数 --over()
    MySql安装与MySQL添加用户、删除用户与授权
    samba服务
    asp.net core系列 58 IS4 基于浏览器的JavaScript客户端应用程序
    asp.net core系列 57 IS4 使用混合流(OIDC+OAuth2.0)添加API访问
  • 原文地址:https://www.cnblogs.com/limei/p/1839576.html
Copyright © 2011-2022 走看看