常用方法
在使用之前,我们先来认识几个ThreadLcoal的常用方法
方法声明 | 描述 |
ThreadLocal() | 创建ThreadLocal对象 |
public void set(T value) | 设置当前线程绑定的局部变量 |
public T get() | 获取的当前线程绑定的局部变量 |
public void remove() | 移除当前线程绑定的局部变量 |
使用案例
package com.jd.rdc.pp.soa.service;
/**
* 需求:线程隔离
* 在多线程并发的场景下,每个线程中的变量都是相互独立
* 线程A:设置(变量1) 获取(变量1)
* 线程B:设置(变量2) 获取(变量2)
* <p>
* ThreadLocal :
* 1、set():将变量绑定到当前线程中
* 2、get():获取当前线程绑定的变量
*/
public class MyDemo {
ThreadLocal<String> t1 = new ThreadLocal<>();
//变量
private String content;
public String getContent() {
// return content;
return t1.get();
}
public void setContent(String content) {
// this.content = content;
//变量content绑定到当前线程他
t1.set(content);
}
public static void main(String[] args) {
MyDemo demo = new MyDemo();
for (int i = 0; i < 5; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
/*
* 每个线程:存一个变量,过一会取出这个变量
*/
demo.setContent(Thread.currentThread().getName() + "的数据");
System.out.println("-----------------------");
System.out.println((Thread.currentThread().getName() + "----->" + demo.getContent()));
}
});
thread.setName("线程" + i);
thread.start();
}
}
}