开发者社区> 技术小甜> 正文
阿里云
为了无法计算的价值
打开APP
阿里云APP内打开

ThreadStaticAttribute和ThreadLocal<T>使用区别总结

简介:
+关注继续查看

ThreadStaticAttribute和ThreadLocal<T>都是提供线程本地存储,ThreadLocal<T>是.net4才提供的。

ThreadStaticAttribute只能标注静态字段,而ThreadLocal<T>可以对实例字段才有效。

如果不标注ThreadStaticAttribute,则多个线程共享一个变量,这样的话会引起冲突的。

 class Program
    {


         static void Main()


        {


            Console.WriteLine("use [ThreadStaticAttribute]");


            for (int i = 0; i < 3; i++)


            {


                Thread newThread = new Thread(ThreadData1.ThreadStaticDemo);


                newThread.Start();


            }


 
            Thread.Sleep(500);


            Console.WriteLine("not use [ThreadStaticAttribute]");


            for (int i = 0; i < 3; i++)


            {


                Thread newThread = new Thread(ThreadData2.ThreadStaticDemo);


                newThread.Start();


            }


            Thread.Sleep(500);


            Console.WriteLine("not use static member, use instance member");


            for (int i = 0; i < 3; i++)


            {


                Thread newThread = new Thread((new ThreadData3()).ThreadStaticDemo);


                newThread.Start();


            }


            Thread.Sleep(500);


            Console.WriteLine("");


            for (int i = 0; i < 3; i++)


            {


                Thread newThread = new Thread(ThreadData4.ThreadStaticDemo);


                newThread.Start();


            }


             Thread.Sleep(500);


            Console.WriteLine("not use [ThreadStaticAttribute], use ThreadLocal<int>");


            for (int i = 0; i < 3; i++)


            {


                Thread newThread = new Thread(ThreadData5.ThreadStaticDemo);


                newThread.Start();


            }


            Thread.Sleep(500);


            Console.WriteLine("not use [ThreadStaticAttribute], use ThreadLocal<int>");


             ThreadLocal<string> ThreadName = new ThreadLocal<string>(() =>


            {


                return "Thread" + Thread.CurrentThread.ManagedThreadId;


            });


 
            // Action that prints out ThreadName for the current thread


            Action action = () =>


            {


                // If ThreadName.IsValueCreated is true, it means that we are not the


                // first action to run on this thread.


                bool repeat = ThreadName.IsValueCreated;


 
                Console.WriteLine("ThreadName = {0} {1}", ThreadName.Value, repeat ? "(repeat)" : "");


            };


 
            // Launch eight of them.  On 4 cores or less, you should see some repeat ThreadNames


            Parallel.Invoke(action, action, action, action, action, action, action, action);


             // Dispose when you are done


            ThreadName.Dispose();


         }


     }


 
    class ThreadData1


    {


        static int threadSpecificData;


        public static void ThreadStaticDemo()


        {


            // Store the managed thread id for each thread in the static


            // variable.


            threadSpecificData = Thread.CurrentThread.ManagedThreadId;


 
            // Allow other threads time to execute the same code, to show


            // that the static data is unique to each thread.


            Thread.Sleep(100);


 
            // Display the static data.


            Console.WriteLine("Data for managed thread {0}: {1}",


                Thread.CurrentThread.ManagedThreadId, threadSpecificData);


 
        }


    }


 
    class ThreadData2


    {


        [ThreadStaticAttribute]//¨¦°?º?¨£¤Attribute¡À¨®¡ä[ThreadStatic] ®?¤¡§¬?


        static int threadSpecificData;


        public static void ThreadStaticDemo()


        {


            // Store the managed thread id for each thread in the static


            // variable.


            threadSpecificData = Thread.CurrentThread.ManagedThreadId;


 
            // Allow other threads time to execute the same code, to show


            // that the static data is unique to each thread.


            Thread.Sleep(100);


 
            // Display the static data.


            Console.WriteLine("Data for managed thread {0}: {1}",


                Thread.CurrentThread.ManagedThreadId, threadSpecificData);


 
        }


    }


 
    class ThreadData3 //使º1®?º¦Ì¤y¤?¤¡§°2¨¦°?º¦Ì?¦?º?¡ì?ê???线?¨¬Ì£¤¨¤使º1®?¡ÂÁ?Ì?À?¢?


    {


        int threadSpecificData;


 
        public void ThreadStaticDemo()


        {


            // Store the managed thread id for each thread in the static


            // variable.


            threadSpecificData = Thread.CurrentThread.ManagedThreadId;


 
            // Allow other threads time to execute the same code, to show


            // that the static data is unique to each thread.


            Thread.Sleep(100);


 
            // Display the static data.


            Console.WriteLine("Data for managed thread {0}: {1}",


                Thread.CurrentThread.ManagedThreadId, threadSpecificData);


         }


    }


     class ThreadData4


    {


        [ThreadStaticAttribute]//¨¦°?º?¨£¤Attribute¡À¨®¡ä[ThreadStatic] ®?¤¡§¬?


        static test t = null;


        public static void ThreadStaticDemo()


        {


            t = new test();


 
            Thread.Sleep(100);


            // Display the static data.


            Console.WriteLine(t.testvalue);


 
        }


    }


     class test


    {


        public int testvalue = 0;


         public test()


        {


            testvalue++;


        }


    }


 
 
    class ThreadData5


    {


        static ThreadLocal<int> threadSpecificData = new ThreadLocal<int>();//only in .net framework 4.0. no need to use [ThreadStaticAttribute]


        static public void ThreadStaticDemo()


        {


            // Store the managed thread id for each thread in the static


            // variable.


            threadSpecificData.Value = Thread.CurrentThread.ManagedThreadId;


             // Allow other threads time to execute the same code, to show


            // that the static data is unique to each thread.


            Thread.Sleep(100);


 
            // Display the static data.


            Console.WriteLine("Data for managed thread {0}: {1}",


                Thread.CurrentThread.ManagedThreadId, threadSpecificData.Value);


         }


    }


 
 

 



















本文转自cnn23711151CTO博客,原文链接:http://blog.51cto.com/cnn237111/545801 ,如需转载请自行联系原作者


版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
ThreadLocal相关使用
ThreadLocal相关使用
23 0
什么是ThreadLocal?
这篇文章是慕课网上一门免费课程《ThreadLocal》的观后总结。这门课将ThreadLocal讲得非常清晰易懂,又深入底层原理和设计思想,是我看过的最好的ThreadLocal的资料,现在把用自己的话,把它整理成文字版本。 总共预计产出四篇文章,这是第一篇。
72 0
ThreadLocal 总结
当工作于多线程中的对象使用 ThreadLocal 维护变量时,ThreadLocal 为每个使用该变量的线程分配一个独立的变量副本。 所以每一个线程都可以独立地改变自己的副本,而不会影响其他线程所对应的副本。从线程的角度看,这个变量就像是线程的本地变量,这也是类名中 “Local” 所要表达的意思。
65 0
用ThreadLocal来优化下代码吧
用ThreadLocal来优化下代码吧
56 0
ThreadLocal
ThreadLocal   ThreadLocal是JDK包提供的,它提供线程本地变量,如果创建一乐ThreadLocal变量,那么访问这个变量的每个线程都会有这个变量的一个副本,在实际多线程操作的时候,操作的是自己本地内存中的变量,从而规避了线程安全问题,如下图所示
48 0
+关注
文章
问答
文章排行榜
最热
最新
相关电子书
更多
低代码开发师(初级)实战教程
立即下载
阿里巴巴DevOps 最佳实践手册
立即下载
冬季实战营第三期:MySQL数据库进阶实战
立即下载