多线程 对变量共享和独享的验证

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

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);
            }
        }
    }
}

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

转载于:https://www.cnblogs.com/limei/archive/2010/09/30/1839576.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值