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 ,如需转载请自行联系原作者


相关文章
|
26天前
|
存储 Java Spring
ThreadLocal用法
ThreadLocal用法
16 0
|
15天前
|
存储 安全 Java
面试题:用过ThreadLocal吗?ThreadLocal是在哪个包下的?看过ThreadLocal源码吗?讲一下ThreadLocal的get和put是怎么实现的?
字节面试题:用过ThreadLocal吗?ThreadLocal是在哪个包下的?看过ThreadLocal源码吗?讲一下ThreadLocal的get和put是怎么实现的?
30 0
|
6月前
|
存储 安全 Java
【ThreadLocal】
【ThreadLocal】
|
3月前
|
存储 安全 Java
ThreadLocal原理讲解
ThreadLocal原理讲解
21 0
|
8月前
|
Java
ThreadLocal全面解析
ThreadLocal全面解析
73 0
|
8月前
|
存储 API
ThreadLocal
ThreadLocal
|
9月前
|
存储 SpringCloudAlibaba Java
浅析ThreadLocal使用及实现原理
提供了线程局部 (thread-local) 变量。这些变量不同于它们的普通对应物,因为访问某个变量(通过其`get` 或 `set`方法)的每个线程都有自己的局部变量,它独立于变量的初始化副本。`ThreadLocal`实例通常是类中的 private static 字段,它们希望将状态与某一个线程(例如,用户 ID 或事务 ID)相关联 。所以ThreadLocal与线程同步机制不同,线程同步机制是多个线程共享同一个变量,而ThreadLocal是为每一个线程创建一个单独的变量副本,故而每个线程都可以独立地改变自己所拥有的变量副本,而不会影响其他线程所对应的副本。可以这么说Th
76 0
浅析ThreadLocal使用及实现原理
|
存储 算法 安全
ThreadLocal原理剖析
ThreadLocal原理剖析
162 0
|
Java 定位技术
ThreadLocal原理
经典八股文之ThreadLocal原理
151 0
|
存储 安全 Java
ThreadLocal 使用详解
ThreadLocal 是线程本地变量。当使用 ThreadLocal 维护变量时,ThreadLocal 为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程
456 0