zoukankan      html  css  js  c++  java
  • ThreadLocal

    作用

    ThreadLocal通过将对象封闭在线程之中,来解决多线程并发的安全性问题。每一个线程均有一个对象,线程只能访问自己的对象,这样,就不存在多线程并发处理单个对象的问题,也就解决了多线程并发的安全性问题。

    原理

    1. Thread对象中有threadLocalMap属性,该属性为map,保存线程所有的ThreadLocal的值。map的键为ThreadLocal本身,值为ThreadLocal对应的本线程的值。
    2. 在使用ThreadLocal时,ThreadLocal会先找到当前线程对象,然后操作当前线程对象的threadLocalMap。
     1     public T get() {
     2         Thread t = Thread.currentThread();
     3         ThreadLocalMap map = getMap(t);
     4         if (map != null) {
     5             ThreadLocalMap.Entry e = map.getEntry(this);
     6             if (e != null) {
     7                 @SuppressWarnings("unchecked")
     8                 T result = (T)e.value;
     9                 return result;
    10             }
    11         }
    12         return setInitialValue();
    13     }
    14 
    15     
    16     ThreadLocalMap getMap(Thread t) {
    17         return t.threadLocals;
    18     }
    1     public void set(T value) {
    2         Thread t = Thread.currentThread();
    3         ThreadLocalMap map = getMap(t);
    4         if (map != null)
    5             map.set(this, value);
    6         else
    7             createMap(t, value);
    8     }

    使用

     1 public class ThreadLocalTest {
     2     private static final ThreadLocal<Integer> count = new ThreadLocal<Integer>() {
     3         @Override
     4         protected Integer initialValue() {
     5             return 0;
     6         }
     7     };
     8 
     9     private static class CountThread extends Thread {
    10         @Override
    11         public void run() {
    12             for (int i = 0;i < 50;i++) {
    13                 count.set(count.get() + 1);
    14             }
    15             System.out.println(count.get());
    16         }
    17     }
    18 
    19     public static void main(String[] args) {
    20         for (int i=0;i < 100;i++) {
    21             new CountThread().start();
    22         }
    23     }
    24 }
  • 相关阅读:
    (转)130道ASP.NET面试题
    (转)c#对象内存模型
    (转)探讨:ASP.NET技术的学习顺序问题
    (转)ASP.NET缓存概念及其应用浅析
    Response.Redirect在新窗口打开网页
    转载 C# 序列化与反序列化意义详解
    简单进制转化
    简单成绩管理系统(没有存盘)
    kali不能ifconfig等简单命令
    蓝桥杯练习之开花(二分法查找)
  • 原文地址:https://www.cnblogs.com/qhdxqxx/p/8876330.html
Copyright © 2011-2022 走看看