package synchronizedtest;
import java.util.Random;
public class ThreadLocalTest {
// private static int data ;
// private static ThreadLocal<Integer> th = new ThreadLocal<Integer>();
static class A {
public void get(){
MD md = MD.getThreadLocalMD();
System.out.println(Thread.currentThread().getName()+" has get data from A : "+"name="+ md.getName()+" age:" +md.getAge());
}
}
static class B{
public void get(){
MD md = MD.getThreadLocalMD();
System.out.println(Thread.currentThread().getName()+" has get data from B : "+"name="+ md.getName()+" age:" +md.getAge());
}
}
public static void main(String[] args) {
new Thread(new Runnable(){
@Override
public void run() {
int data = new Random().nextInt();
// MD.getThreadInstance().setName("name" + data);
// MyThreadScopeData.getThreadInstance().setAge(data);
MD.getThreadLocalMD().setName("name" + data);
MD.getThreadLocalMD().setAge(data);
System.out.println(Thread.currentThread().getName()+" has put data : "+ data);
new A().get();
new B().get();
}
}).start();
new Thread(new Runnable(){
@Override
public void run() {
int data = new Random().nextInt();
MD md = MD.getThreadLocalMD();
md.setName("name"+data);
md.setAge(data);
System.out.println(Thread.currentThread().getName()+" has put data : "+ data);
new A().get();
new B().get();
}
}).start();
}
}
class MD{
private MD(){
}
public static MD getThreadLocalMD(){
if(instance == null){
instance = new MD();
//在这里继承ThreadLocal类。让每一个线程获得一个独立的单例MD对象。同一个线程中共享MD对象,但不同线程之间又不互相影响。
th.set(instance);
}
return instance;
}
private static MD instance = null;
private static ThreadLocal<MD> th = new ThreadLocal<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;
}
}
运行结果是这么个:
Thread-1 has put data : -606023922
Thread-0 has put data : -2073132774
Thread-0 has get data from A : name=name-2073132774 age:-2073132774
Thread-1 has get data from A : name=name-2073132774 age:-2073132774
Thread-1 has get data from B : name=name-2073132774 age:-2073132774
Thread-0 has get data from B : name=name-2073132774 age:-2073132774
明显没有达到每个线程各自取各自的变量的效果,哪里出错了,呵呵,自己看不出来的时候得找别人帮帮忙啦! |
|