多线程学习--通过单例模式来实现多个线程中的数据共享

来源:互联网 发布:红外枪型网络摄像机 编辑:程序博客网 时间:2024/05/29 04:37
package Demo6;
import java.util.Random;
public class ThreadlocalTest {
//private static ThreadLocal<Integer> tl =new ThreadLocal<Integer>();
private static ThreadLocal<MyThreadScopeData> msd=new ThreadLocal<MyThreadScopeData>();
public static void main(String[] args) {
for(int i=0;i<2;i++){
new Thread(new Runnable(){
@Override
public void run() {
int data =new Random().nextInt();
//tl.set(data);
/*MyThreadScopeData mydata=new  MyThreadScopeData();
mydata.setAge(data);
mydata.setName("name"+data);
msd.set(mydata);*/
MyThreadScopeData.getInstance().setAge(data);
MyThreadScopeData.getInstance().setName("name"+data);
System.out.println(data+""+Thread.currentThread().getName());
new ABB().getAB();
new ACC().getAC();
}
}).start();
}
}
static class ABB{
public void getAB(){
MyThreadScopeData mtsd =MyThreadScopeData.getInstance();
System.out.println("age"+mtsd.getAge()+"name"+mtsd.getName());
   //int data=tl.get();
//System.out.println(data+""+Thread.currentThread().getName());
}
}
static class ACC{
public void getAC(){
MyThreadScopeData mtsd =MyThreadScopeData.getInstance();
System.out.println("age"+mtsd.getAge()+"name"+mtsd.getName());
//int data=tl.get();
//System.out.println(data+""+Thread.currentThread().getName());
}
}
 static  class MyThreadScopeData{
//饿汉式
/* private MyThreadScopeData(){
}
public static MyThreadScopeData getInstance(){
return instance;
}
private static MyThreadScopeData instance =new MyThreadScopeData();*/
//懒汉式
/* private MyThreadScopeData(){}
public static synchronized MyThreadScopeData getInstance(){
if(instance ==null){
instance =new MyThreadScopeData();
}
return instance;
}
private static MyThreadScopeData instance =null;*/
private MyThreadScopeData(){}
public static  MyThreadScopeData getInstance(){
MyThreadScopeData instance = msdd.get();
if(instance ==null){
instance =new MyThreadScopeData();
msdd.set(instance);
}
return instance;
}
private static  ThreadLocal<MyThreadScopeData> msdd =new ThreadLocal<MyThreadScopeData>();
       
 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;
}
private String name;
 private int age;
 
  }
}
0 0
原创粉丝点击