为了凑字,把oracle文档里介绍ThreadLocal抄过来

public class ThreadLocal<T>
extends Object
This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable.ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

For example, the class below generates unique identifiers local to each thread. A thread's id is assigned the first time it invokes ThreadId.get() and remains unchanged on subsequent calls.

 import java.util.concurrent.atomic.AtomicInteger;

 public class ThreadId {
// Atomic integer containing the next thread ID to be assigned
private static final AtomicInteger nextId = new AtomicInteger(0); // Thread local variable containing each thread's ID
private static final ThreadLocal<Integer> threadId =
new ThreadLocal<Integer>() {
@Override protected Integer initialValue() {
return nextId.getAndIncrement();
}
}; // Returns the current thread's unique ID, assigning it if necessary
public static int get() {
return threadId.get();
}
}

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

接下来一个示例

import java.util.Random;

public class ThreadLocalTest {

    public static void main(String[] args) {
for (int i = 0; i < 2; i++) { new Thread(new Runnable(){
public void run() {
int age = new Random().nextInt();
MyData md = MyData.getInstance();
md.setAge(age);
md.setName(Thread.currentThread().getName()); System.out.println(Thread.currentThread().getName()+ " age is "+age);
new A().get();
new B().get(); };
}).start(); }
} static class A{
public void get(){
MyData md = MyData.getInstance();
System.out.println(Thread.currentThread().getName()+" A age "+md.getAge() + " name = "+md.getName());
}
} static class B{
public void get(){
MyData md = MyData.getInstance();
System.out.println(Thread.currentThread().getName()+" B age "+md.getAge() + " name = "+md.getName());
}
}
} class MyData{ private MyData(){
} public static MyData md = null;
private static ThreadLocal<MyData> tl = new ThreadLocal<MyData>(); public synchronized static MyData getInstance(){
md = tl.get();
if(null==md){
md = new MyData();
tl.set(md);
}
return md;
} private String name; private int age; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} }

想了半天不知如何表达,语文太差。

推荐博客

http://www.cnblogs.com/dolphin0520/p/3920407.html

java多线程学习-ThreadLocal的更多相关文章

  1. Java多线程学习(五)线程间通信知识点补充

    系列文章传送门: Java多线程学习(二)synchronized关键字(1) Java多线程学习(二)synchronized关键字(2) Java多线程学习(三)volatile关键字 Java多 ...

  2. Java多线程学习笔记

    进程:正在执行中的程序,其实是应用程序在内存中运行的那片空间.(只负责空间分配) 线程:进程中的一个执行单元,负责进程汇总的程序的运行,一个进程当中至少要有一个线程. 多线程:一个进程中时可以有多个线 ...

  3. Java多线程学习(转载)

    Java多线程学习(转载) 时间:2015-03-14 13:53:14      阅读:137413      评论:4      收藏:3      [点我收藏+] 转载 :http://blog ...

  4. java多线程学习笔记——详细

    一.线程类  1.新建状态(New):新创建了一个线程对象.        2.就绪状态(Runnable):线程对象创建后,其他线程调用了该对象的start()方法.该状态的线程位于可运行线程池中, ...

  5. 【转】Java多线程学习

    来源:http://www.cnblogs.com/samzeng/p/3546084.html Java多线程学习总结--线程概述及创建线程的方式(1) 在Java开发中,多线程是很常用的,用得好的 ...

  6. JAVA多线程学习笔记(1)

    JAVA多线程学习笔记(1) 由于笔者使用markdown格式书写,后续copy到blog可能存在格式不美观的问题,本文的.mk文件已经上传到个人的github,会进行同步更新.github传送门 一 ...

  7. Java多线程学习(六)Lock锁的使用

    系列文章传送门: Java多线程学习(二)synchronized关键字(1) Java多线程学习(二)synchronized关键字(2) Java多线程学习(三)volatile关键字 Java多 ...

  8. Java多线程学习(四)等待/通知(wait/notify)机制

    转载请备注地址:https://blog.csdn.net/qq_34337272/article/details/79690279 系列文章传送门: Java多线程学习(一)Java多线程入门 Ja ...

  9. Java多线程学习(三)volatile关键字

    转载请备注地址:https://blog.csdn.net/qq_34337272/article/details/79680693 系列文章传送门: Java多线程学习(一)Java多线程入门 Ja ...

随机推荐

  1. libvirt

    http://libvirt.org/index.html libvirt supports: The KVM/QEMU Linux hypervisor The Xen hypervisor on ...

  2. Windows环境下使用Redis缓存工具的图文详细方法

    一.简介 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合)和zset(有序集合). ...

  3. 使用Visual Studio Code搭建TypeScript开发环境

    使用Visual Studio Code搭建TypeScript开发环境 1.TypeScript是干什么的 ? TypeScript是由微软Anders Hejlsberg(安德斯·海尔斯伯格,也是 ...

  4. HackerRank "New Year Chaos"

    Two tricks here: 1. Counting no. of inversed pairs - using Merge Sort, nothing special 2. How to che ...

  5. oracle两列相同的去重

    源地址:https://zhidao.baidu.com/question/66722841.html 1.不含大字段(clob等)的表格: 1 2 3 4 5 6 7 8 9 --例子表格:crea ...

  6. Node以数据块的形式读取文件

    在Node中,http响应头信息中Transfer-Encoding默认是chunked. Transfer-Encoding:chunked Node天生的异步机制,让响应可以逐步产生. 这种发送数 ...

  7. [EventBus源码解析] 订阅者处理消息的四种ThreadMode

    前言 在前面,我们探讨了如何在自己的代码中引入EventBus,进行基本的事件分发/监听:对注册观察者与事件发送的过程进行了浅析.从之前的学习中,我们了解到,EventBus一共有4种onEvent方 ...

  8. metasploit升级(BT5)

    1.apt-get update 2.apt-get install metasploit 3.修改文件:/opt/metasploit/ruby/lib/ruby/1.9.1/i686-linux/ ...

  9. JS-改变页面的颜色(一)

    需求:点击页面的按钮,改变页面的颜色 思路:一先画出最简单的页面,二想办法获取页面的body节点,三想办法修改body节点的背景颜色属性,四通过一个方法获取随机的颜色值 简单的代码片段如下所示: &l ...

  10. iOS开发中的4种数据持久化方式【一、属性列表与归档解档】

    iOS中的永久存储,也就是在关机重新启动设备,或者关闭应用时,不会丢失数据.在实际开发应用时,往往需要持久存储数据的,这样用户才能在对应用进行操作后,再次启动能看到自己更改的结果与痕迹.ios开发中, ...