jdk src 学习 Threadlocal
2024-09-27 14:27:00
示例:
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 的作用在于,将某些变量绑定到线程中去, 提供一种,线程安全的方式操作某些变量。
最新文章
- 第4月第1天 makefile automake
- C# MVC 页面静态化导致的问题
- RBL开发笔记一
- Oracle游标总结
- jquery api 笔记(2) 事件 事件对象
- javascript:void(0)知多少
- animation之translate、scale、alpha、rotate动画效果呈现
- 利用Redis keyspace notification(键空间通知)实现过期提醒
- Codeforces1153F Serval and Bonus Problem 【组合数】
- [蓝桥杯]PREV-23.历届试题_数字游戏
- Python module ---- abc
- MySQL中int(m)的含义
- swift 学习- 26 -- 泛型
- RN与webview通讯
- python----面向对象(2)
- latex学习(三)
- python oracle 查询返回字典
- startActivity时报错Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVI
- Android深入浅出之Binder机制(转)
- Ubuntu16.04下添加打印机FujiXerox CP116w