• java Thread之ThreadLocal(线程局部变量)


    ThreadLocal即线程局部变量。

    功能:为每个使用该变量的线程,提供一个该变量的副本。

    其实ThreadLocal中拥有一个Map,它是线程->变量的映射。

    主要方法有三个,set,get,initValue。

    set与get的作用不用多讲,主要是initValue,它默认返回的是null,子类可以通过重载该方法,来改变默认值。 

      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     }
     9     
    10     
    11     public T get() {
    12         Thread t = Thread.currentThread();
    13         ThreadLocalMap map = getMap(t);
    14         if (map != null) {
    15             ThreadLocalMap.Entry e = map.getEntry(this);
    16             if (e != null)
    17                 return (T)e.value;
    18         }
    19         return setInitialValue();
    20     }
    21     
    22     
    23     protected T initialValue() {
    24         return null;
    25     }

     使用示例:

     1 package com.cody.test.thread;
     2 
     3 public class ThreadLocalTest {
     4 
     5     private static ThreadLocal<String> mThreadLocal = new ThreadLocal<String>();
     6     private static Business business = new Business();
     7     public static void main(String[] args) {
     8         new Thread(new Runnable() {
     9             
    10             @Override
    11             public void run() {
    12                 business.sub();
    13             }
    14         }).start(); //开始一个线程
    15         
    16         business.main();
    17     }
    18     
    19     public static class Business{
    20         
    21         public void sub(){
    22             for(int i = 0;i < 10;i ++){
    23                 mThreadLocal.set(String.valueOf(i));
    24                 try {
    25                     Thread.sleep(40);
    26                 } catch (InterruptedException e) {
    27                     e.printStackTrace();
    28                 }
    29                 System.out.println(Thread.currentThread().getName() + " : " + mThreadLocal.get());
    30             }
    31         }
    32         
    33         public void main(){
    34             for(int i = 0;i < 20;i ++){
    35                 mThreadLocal.set(String.valueOf(i));
    36                 try {
    37                     Thread.sleep(20);
    38                 } catch (InterruptedException e) {
    39                     e.printStackTrace();
    40                 }
    41                 System.out.println(Thread.currentThread().getName() + " : " + mThreadLocal.get());
    42             }
    43         }
    44     }
    45 

    46 } 

  • 相关阅读:
    解决VMwave下卡死的办法
    深度探索C++对象模型第四章:函数语义学
    cc
    tbb库的使用
    10内核同步方法
    哈希
    django 和restful framework 初始配置轻松搞定
    linux有趣动画--代码雨
    linux有趣开机图标--佛祖保佑
    Socket是什么,通俗易懂点说
  • 原文地址:https://www.cnblogs.com/cody1988/p/2536069.html
Copyright © 2020-2023  润新知