ThreadLocal的使用
来源:互联网 发布:nginx squid 缓存 编辑:程序博客网 时间:2024/06/01 10:25
public class TestThreadLocal {private static ThreadLocal<Integer> tl = new ThreadLocal<Integer>(){protected Integer initialValue() {return 0;};};public int getNext() {tl.set(tl.get() + 1);return tl.get();}public static void main(String[] args) {//线程共享testThreadLocal对象,此对象中有 ThreadLocal<Integer> tl//ThreadLocal通过ThreadLocalMap为每个线程创建一个Integer对象的副本TestThreadLocal testThreadLocal = new TestThreadLocal();Thread thread1 = new Thread(new MyThread(testThreadLocal), "t1");Thread thread2 = new Thread(new MyThread(testThreadLocal), "t2");thread1.start();thread2.start();}private static class MyThread implements Runnable {private TestThreadLocal t;public MyThread(TestThreadLocal t) {this.t = t;}@Overridepublic void run() {for(int i = 0; i < 3; i++) {System.out.println(Thread.currentThread().getName() + "-" + t.getNext());}}}}
运行结果如下:
t1-1
t2-1
t1-2
t2-2
t1-3
t2-3
t2-1
t1-2
t2-2
t1-3
t2-3
可以看出,各个线程的局部变量的值互不干扰~
阅读全文
0 0
- ThreadLocal的使用- -
- ThreadLocal的使用
- ThreadLocal 的使用
- ThreadLocal的使用
- 关于ThreadLocal的使用
- Threadlocal类的使用
- ThreadLocal的使用
- ThreadLocal的使用
- ThreadLocal的使用
- java ThreadLocal的使用
- 关于ThreadLocal的使用
- ThreadLocal的优雅使用
- ThreadLocal的使用
- 关于ThreadLocal的使用
- ThreadLocal的使用
- ThreadLocal的使用
- ThreadLocal 的使用
- ThreadLocal的使用
- 安装ubuntu 16.04后要做的事情
- 有关 C++ 内存对齐的测试
- Linux_Kafka 集群安装笔记
- ArcSDE版本学习总结(1)
- android沉浸式简单实现
- ThreadLocal的使用
- python 接口测试response返回数据对比
- 作为新人,我入行了,<序>
- css样式缓存
- 搭建springmvc+spring+mybatis+IntelliJ IDEA例子
- 约束文件
- linux日志对应内容
- Java 8 lambda表达式
- SceneManager.LoadScene