線程學習筆記【5】--ThreadLocal應用
基本的ThreadLocal使用
public class ThreadLocalTest {
static ThreadLocal tl=new ThreadLocal();
public static void main(String[] args) {
for(int i=0;i<2;i++){
new Thread(new Runnable(){
int data =new Random().nextInt();
public void run() {
System.out.println(Thread.currentThread().getName()+"存入的數據是 "+data);
tl.set(data); //存到了當前線程
new A().getThreadData();
}
}).start();
}
}
static class A{ //靜態類相當于一個外部類
public void getThreadData(){
System.out.println("data is "+tl.get());
}
}
}
結果可能是
Thread-0存入的數據是 1997234255
Thread-1存入的數據是 267171693
data is 1997234255
data is 267171693
通過包裝對象非常爛的使用方式
class MyThreadScopeData{
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;
}
}
public class ThreadLocalTest {
static ThreadLocal<MyThreadScopeData> myThreadScopeData=
new ThreadLocal<MyThreadScopeData>();
public static void main(String[] args) {
for(int i=0;i<2;i++){
new Thread(new Runnable(){
int data =new Random().nextInt();
public void run() {
MyThreadScopeData mydata=new MyThreadScopeData();
mydata.setName("name is name"+data);
mydata.setAge(data);
//把對象存入ThreadLocal 這樣的做法非常爛!!!!!
myThreadScopeData.set(mydata);
new B().showThreadScopeData();
}
}).start();
}
}
static class B{
public void showThreadScopeData(){
System.out.println(myThreadScopeData.get().getName());
System.out.println("age is "+myThreadScopeData.get().getAge());
}
}
}
}
標準使用方式
/**
* 單列線程
* 在線程中范圍內任意地方調,得到都是同一個實例對象
* 把ThreadLocal封裝到單列的內部
*/
class ThreadSingle{
private ThreadSingle(){}
public static ThreadLocal<ThreadSingle> map=new ThreadLocal<ThreadSingle>();
//不需要加synchronized,即便有第2個線程進入,但拿到的map.get()是獨有的。
public static ThreadSingle getThreadInstance(){ //方法得到是與本線程相關的實例
ThreadSingle obj=map.get();
/**
* 如果A進入時obj=null,剛創建完還沒賦值,此時B線程進入,但B和A沒有關系。
*/
if(obj==null){
obj=new ThreadSingle();
map.set(obj);
}
return obj;
}
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;
}
}
public class ThreadLocalTest { public static void main(String[] args) { for(int i=0;i<2;i++){ new Thread(new Runnable(){ int data =new Random().nextInt(); public void run() { ThreadSingle.getThreadInstance().setName("name"+data); ThreadSingle.getThreadInstance().setAge(data); new C().showData(); } }).start(); } }