发表文章 返回首页
当前位置: bitsCN.com > JAVA > 高级技术 > 多线程 >

Java多线程之ThreadLocal

时间:2008-09-08 00:00来源:中国网管联盟 作者:bitsCN整理 点击:
ThreadLocal的核心思想很简单:为每个独立的线程提供一个变量的副本。 ThreadLocal则使用了“拷贝副本”的方式,人人有份,你用你的,我用我的,大家互不影响,是“以空间换时间”。每个线程修改变量时,实际上修改
  

    ThreadLocal的核心思想很简单:为每个独立的线程提供一个变量的副本。

中国网管联盟www.bitscn.com

    ThreadLocal则使用了“拷贝副本”的方式,人人有份,你用你的,我用我的,大家互不影响,是“以空间换时间”。每个线程修改变量时,实际上修改的是变量的副本,不怕影响到其它线程。 网管联盟www.bitsCN.com

    为了加深对ThreadLocal的理解,下面我使用一个例子来演示ThreadLocal如何隔离线程间的变量访问和修改:

【1】SerialNum类 网管联盟www.bitsCN.com

package example.thread.threadLocal;

public class SerialNum {

    
private static int nextSerialNum = 1;

    @SuppressWarnings(
"unchecked")
网管联盟www.bitsCN.com

    
private static ThreadLocal serialNum = new ThreadLocal() {
        
protected synchronized Object initialValue() {
            return new Integer(nextSerialNum++);      
54ne.com
        }                                                           
    };

    
public static int get() {
        
return ((Integer) (serialNum.get())).intValue(); 网管联盟www.bitsCN.com
    }
    
    @SuppressWarnings(
"unchecked")
    
public static void set(Integer newSerial){
        serialNum.set(newSerial);
    }
}

【2】GetSerialNumThread package example.thread.threadLocal;
中国网管联盟www、bitsCN、com


public class GetSerialNumThread implements Runnable {

    
public static void main(String args[]) {

        GetSerialNumThread serialNumGetter 
= new GetSerialNumThread();

网管网bitsCN_com


        Thread t1 
= new Thread(serialNumGetter, "Thread A");
        Thread t2 
= new Thread(serialNumGetter, "Thread B");
网管网bitsCN.com

        t1.start();
        
try {
            t1.join();
        } 
catch (InterruptedException e) {
            e.printStackTrace();
        }    
        t2.start();            
    }

    
public void run() {

网管联盟www.bitsCN.com


        
int mySerialNum = getSerialNum();
        System.out.println("线程 " + Thread.currentThread().getName()
                
+ " 获取到的序列号是" + mySerialNum);

中国网管论坛bbs.bitsCN.com


        System.out.println(
"线程 " + Thread.currentThread().getName()
                
+ " 修改了序列号为" + (mySerialNum * 3));
54com.cn

        setSerialNum(mySerialNum * 3);

        System.out.println(
"线程 " + Thread.currentThread().getName()
                
+ " 再次获得的序列号是" + getSerialNum()); 中国网管联盟www.bitscn.com
    }

    
private int getSerialNum() {
        
return SerialNum.get();
    }

    
private void setSerialNum(int newSerialNum) {
        SerialNum.set(
new Integer(newSerialNum)); 网管联盟www.bitsCN.com
    }
}

运行的结果如下:
线程 Thread A 获取到的序列号是1
线程 Thread A 修改了序列号为3
线程 Thread A 再次获得的序列号是3
线程 Thread B 获取到的序列号是2
线程 Thread B 修改了序列号为6
线程 Thread B 再次获得的序列号是6

    可见第一个线程在调用SerialNum.set(int)方法修改static变量时,其实修改的是它自己的副本,而不是修改本地变量,第二个线程在初始化的时候拿到的序列号是2而不是7。

    为什么会这样呢?明明serialNum是静态变量啊?其实我们只需要看看ThreadLocal的内部构造就知道了:

A. ThreadLocal的get()方法:
 /**
     * Returns the value in the current thread's copy of this thread-local

中国网管联盟www、bitsCN、com


     * variable.  Creates and initializes the copy if this is the first time
     * the thread has called this method.
     *
     * 
@return the current thread's value of this thread-local
     
*/
    
public T get() {
        Thread t 
= Thread.currentThread(); 54com.cn
        ThreadLocalMap map 
= getMap(t);
        
if (map != null)
            
return (T)map.get(this);

        
// Maps are constructed lazily.  if the map for this thread 中国网管联盟www、bitsCN、com
        
// doesn't exist, create it, with this ThreadLocal and its
        
// initial value as its only entry.
        T value = initialValue();
        createMap(t, value);
        
return value;
    }
54ne.com
B. ThreadLocal的set()方法: /**
     * Sets the current thread's copy of this thread-local variable
     * to the specified value.  Many applications will have no need for
     * this functionality, relying solely on the {
@link #initialValue}
     * method to set the values of thread-locals.
     *
     * 
@param value the value to be stored in the current threads' copy of

54ne.com


     *        this thread-local.
     
*/
    
public void set(T value) {
        Thread t 
= Thread.currentThread();
        ThreadLocalMap map 
= getMap(t);
        
if (map != null) 网管联盟www.bitsCN.com
            map.set(
this, value);
        
else
            createMap(t, value);
    }

    可以看到ThreadLocal在内部维护了一个Map,将变量的值和线程绑定起来,get/set方法都是对该线程对应的value进行操作,所以不会影响到其它线程。
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
最新评论 查看所有评论
发表评论 查看所有评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 密码: 验证码:
发布者资料
admin 查看详细资料 发送留言 加为好友 用户等级:注册会员 注册时间:2008-05-08 23:05 最后登录:2009-01-06 01:01
推荐内容