示例:

import java.io.Serializable;

public class TestThreadLocal implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1279921928557717157L; int age; public static void main(String[] argv) throws Exception { TestThreadLocal tt = new TestThreadLocal(); Testthread t1 = new Testthread(tt);
Testthread t2 = new Testthread(tt);
Testthread t3 = new Testthread(tt); t1.start();
t2.start();
t3.start(); } static int ii = ;
// static Integer ii = 0; // public Integer getIi() {// 这个方式不行
// ii ++;
// return ii;
// } public Integer getIi() {
// tl.set( ii ++ ); // 这个方式也不行, 必须要下面的方式。
tl.set(tl.get() + );
return tl.get();
} /**
* { } 内部的初始化是必须的。 否则出现 nullpointexception
*/
ThreadLocal<Integer> tl = new ThreadLocal<Integer>() {
protected Integer initialValue() {
ii = ;
return ii;
};
}; } class Testthread extends Thread { TestThreadLocal ttl; public Testthread(TestThreadLocal ttl) {
this.ttl = ttl;
} @Override
public void run() {
String name2 = Thread.currentThread().getName();
for (int i = ; i < ; i++) {
System.out.println(" name " + name2 + ttl.getIi());
}
}
}
ThreadLocal 的作用在于,将某些变量绑定到线程中去, 提供一种,线程安全的方式操作某些变量。

最新文章

  1. 第4月第1天 makefile automake
  2. C# MVC 页面静态化导致的问题
  3. RBL开发笔记一
  4. Oracle游标总结
  5. jquery api 笔记(2) 事件 事件对象
  6. javascript:void(0)知多少
  7. animation之translate、scale、alpha、rotate动画效果呈现
  8. 利用Redis keyspace notification(键空间通知)实现过期提醒
  9. Codeforces1153F Serval and Bonus Problem 【组合数】
  10. [蓝桥杯]PREV-23.历届试题_数字游戏
  11. Python module ---- abc
  12. MySQL中int(m)的含义
  13. swift 学习- 26 -- 泛型
  14. RN与webview通讯
  15. python----面向对象(2)
  16. latex学习(三)
  17. python oracle 查询返回字典
  18. startActivity时报错Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVI
  19. Android深入浅出之Binder机制(转)
  20. Ubuntu16.04下添加打印机FujiXerox CP116w

热门文章

  1. c++中计算程序执行时间
  2. 在CAD二次开发中使用进度条
  3. Ubuntu16.04 LTS软件中心闪退及修改阿里源
  4. Boost:shared_memory_object --- 共享内存
  5. .NET使用Task动态创建多任务多线程并行程序计算Redis集群keys计算
  6. Java学习——Applet菜单
  7. IRQL Ring0实现
  8. python之路——1
  9. Linux镜像源
  10. React 懒加载组件