理解ThreadLocal
来源:互联网 发布:网络诈骗多久能破案 编辑:程序博客网 时间:2024/05/17 08:04
跟以前的文章一样,还是先来一个例子。
public class ThreadLocalDemo implements Runnable {
//创建线程局部变量studentLocal,在后面你会发现用来保存Student对象 private final static ThreadLocal<Student> studentLocal = new ThreadLocal<Student> (); public static void main(String[] agrs) { ThreadLocalDemo td = new ThreadLocalDemo(); Thread t1 = new Thread(td, "a"); Thread t2 = new Thread(td, "b"); t1.start(); t2.start(); } public void run() { accessStudent(); } /** * 示例业务方法,用来测试 */ public void accessStudent() { //获取当前线程的名字 String currentThreadName = Thread.currentThread().getName(); System.out.println(currentThreadName + " is running!"); //产生一个随机数并打印 Random random = new Random(); int age = random.nextInt(100); System.out.println("thread " + currentThreadName + " set age to:" + age); //获取一个Student对象,并将随机数年龄插入到对象属性中 Student student = getStudent(); student.setAge(age); System.out.println("thread " + currentThreadName + " first read age is:" + student.getAge()); try { Thread.sleep(500); } catch (InterruptedException ex) { ex.printStackTrace(); } System.out.println("thread " + currentThreadName + " second read age is:" + student.getAge()); } protected Student getStudent() { //获取本地线程变量并强制转换为Student类型 Student student = (Student) studentLocal.get(); //线程首次执行此方法的时候,studentLocal.get()肯定为null if (student == null) { //创建一个Student对象,并保存到本地线程变量studentLocal中 student = new Student(); studentLocal.set(student); } return student; }}
public class Student { private int age = 0; //年龄 public int getAge() { return this.age; } public void setAge(int age) { this.age = age; }}
结果:
写道
a is running!
b is running!
thread b set age to:35
thread a set age to:69
thread b first read age is:35
thread a first read age is:69
thread a second read age is:69
thread b second read age is:35
b is running!
thread b set age to:35
thread a set age to:69
thread b first read age is:35
thread a first read age is:69
thread a second read age is:69
thread b second read age is:35
结论:ThreadLocal用于解决线程之间数据隔离问题。Synchronized使用同步的方式解决数据的共享。
- 理解ThreadLocal
- 理解ThreadLocal
- 理解ThreadLocal
- 理解ThreadLocal
- 理解ThreadLocal
- 理解ThreadLocal
- 理解ThreadLocal
- 理解ThreadLocal
- 理解ThreadLocal
- 理解ThreadLocal
- 理解Threadlocal
- 理解ThreadLocal
- 理解ThreadLocal
- 理解ThreadLocal
- 理解ThreadLocal
- 理解ThreadLocal
- 理解ThreadLocal
- 理解ThreadLocal
- Servlet中context和session相关listener
- 最近该读哪些书(一)
- 中国互联网巨头公司面试
- Extjs源码——extend
- 使用JS闭包控制对象属性访问范围
- 理解ThreadLocal
- 最近该读哪些书(二)
- JS中事件流测试
- 使用DOM实现事件响应函数的注册、删除及事件传递的终止
- 项目管理之项目基础概念
- 最近该读哪些书(三)
- Java RTTI
- 博客搬家
- [置顶] 问题集锦一