Java基础加强 线程范围内数据共享设计模式

来源:互联网 发布:淘宝凑单什么意思 编辑:程序博客网 时间:2024/06/05 06:52

                         线程范围内数据共享设计模式

获得某个类的实例,且该实例对象是与本线程相关的,则使用类似单利设计模式的ThreadLocal方法。

例如如下代码:

 

package Cn.itcast;

 

import java.util.Random;

 

public class ThreadLocalTest {

 

/**

 * @param args

 */

public static void main(String[] args) {

// TODO 自动生成的方法存根

ThreadLocalTest tlt=new ThreadLocalTest();

final A a=tlt.new A();

final B b=tlt.new B();

for(int i=0;i<2;i++){

new Thread(new Runnable(){

public void run(){

int age=new Random().nextInt();

System.out.println("线程:"+Thread.currentThread().getName()+"开始放入数据"+age);

ThreadInstance instanc=ThreadInstance.getThreadInstance();

instanc.setName(""+age);

instanc.setAge(age);

a.get();

b.get();

}

}).start();

}

 

}

class A{

public void get(){

ThreadInstance instanc=ThreadInstance.getThreadInstance();

System.out.println("线程"+Thread.currentThread().getName()+"在A中获得姓名为:"+instanc.getName()+"年龄为"+instanc.getAge());

}

}

class B{

public void get(){

ThreadInstance instanc=ThreadInstance.getThreadInstance();

System.out.println("线程"+Thread.currentThread().getName()+"在B中获得姓名为:"+instanc.getName()+"年龄为"+instanc.getAge());

}

}

 

}

 

 

 

 

 

class ThreadInstance{

private String name;

private int age;

private ThreadInstance(){}

static ThreadLocal<ThreadInstance> th=new ThreadLocal<ThreadInstance>();

public static ThreadInstance getThreadInstance(){

ThreadInstance instance=th.get();

if(instance==null){

instance=new ThreadInstance();

th.set(instance);

}

return instance;

}

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;

}

}