设为首页 加入收藏

TOP

Java线程:深入ThreadLocal
2014-11-13 09:30:20 来源: 作者: 【 】 浏览:25
Tags:Java 线程 深入 ThreadLocal

  ThreadLocal与线程成员变量还有区别,ThreadLocal该类提供了线程局部变量。这个局部变量与一般的成员变量不一样,ThreadLocal的变量在被多个线程使用时候,每个线程只能拿到该变量的一个副本,这是Java API中的描述,通过阅读API源码,发现并非副本,副本什么概念?克隆品 或者是别的样子,太模糊。


  准确的说,应该是ThreadLocal类型的变量内部的注册表(Map )发生了变化,但ThreadLocal类型的变量本身的确是一个,这才是本质!


  下面就做个例子:


  一、标准例子


  定义了MyThreadLocal类,创建它的一个对象tlt,分别给四个线程使用,结果四个线程tlt变量并没有出现共用现象,二是各用各的,这说明,四个线程使用的是tlt的副本(克隆品)。


  /**


  * 使用了ThreadLocal的类


  *


  */


  public class MyThreadLocal {


  //定义了一个ThreadLocal变量,用来保存int或Integer数据


  private ThreadLocal tl = new ThreadLocal () {


  @Override


  protected Integer initialValue() {


  return 0;


  }


  };


  public Integer getNextNum() {


  //将tl的值获取后加1,并更新设置t1的值


  tl.set(tl.get() + 1);


  return tl.get();


  }


  }


  /**


  * 测试线程


  *


  */


  public class TestThread extends Thread {


  private MyThreadLocal tlt = new MyThreadLocal();


  public TestThread(MyThreadLocal tlt) {


  this.tlt = tlt;


  }


  @Override


  public void run() {


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


  System.out.println(Thread.currentThread().getName() + "\t" + tlt.getNextNum());


  }


  }


  }


  /**


  * ThreadLocal测试


  *


  */


  public class Test {


  public static void main(String[] args) {


  MyThreadLocal tlt = new MyThreadLocal();


  Thread t1 = new TestThread(tlt);


  Thread t2 = new TestThread(tlt);


  Thread t3 = new TestThread(tlt);


  Thread t4 = new TestThread(tlt);


  t1.start();


  t2.start();


  t3.start();


  t4.start();


  }


  }


  可以看出,三个线程各自独立编号,互不影响:


  Thread-0 1


  Thread-1 1


  Thread-0 2


  Thread-1 2


  Thread-0 3


  Thread-1 3


  Thread-2 1


  Thread-3 1


  Thread-2 2


  Thread-3 2


  Thread-2 3


  Thread-3 3


  Process finished with exit code 0


  tlt对象是一个,废话tl对象也是一个,因为组合关系是一对一的。但是tl对象内部的Map随着线程的增多,会创建很多Integer对象。只是Integer和int已经通用了。所以感觉不到Integer的对象属性。


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Java线程:线程私有变量 下一篇JavaServletAPI中文说明文档(1)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: