单列模式下的ThreadLocal
ThreadLocal详细介绍:http://www.cnblogs.com/ieage/archive/2012/05/16/2505426.html
import java.util.Random; /** * 通过单列模式将ThreadLocal屏蔽,这样每个线程的对象的数据都不会出产生重复 * 把数据封装成一个类,这样可以保存多个数据,每个数据用单列模式和ThreadLocal保证了对象在同一个线程共享不会产生混乱 * @author MrRock * */ public class ThreadLocalByObject { 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(); User user = User.getThreadInstance(); //单列获取 user.setAge(data); user.setName(String.valueOf(data)); new A().getData(); new B().getData(); } }).start(); } } static class A{ public void getData(){ User user = User.getThreadInstance(); //单列获取 System.out.println("ClassA---> : " + Thread.currentThread().getName() + " name: " + user.getName() +" age: "+user.getAge()); } } static class B{ public void getData(){ User user = User.getThreadInstance(); //单列获取 System.out.println("ClassB---> : " + Thread.currentThread().getName() + " name: " + user.getName() +" age: "+user.getAge()); } } } //单列模式 class User { //保证线程的唯一性,每个线程之间数据不会混乱 private User(){}; public static /*Synchronized*/ User getThreadInstance(){ //使用ThreadLocal就不用Synchronized User instance = map.get(); //从ThreadLocal获取 if(instance == null){ instance = new User(); map.set(instance); //写入ThreadLocal } return instance; } //private staic User instance = new User(); //在ThreadLocal写入一个User对象 private static ThreadLocal<User> map = new ThreadLocal<User>(); 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; } }