1 package cn.lyy.thread; 2 3 import java.util.Random; 4 5 6 /** 7 * 基于单例模式的基础上,使用ThreadLocal为每一个进入的线程生成一个实例, 8 * 用来对数据的访问修改而不影响到别的线程对同一个数据的修改 9 * @author Administrator 10 * 11 */ 12 public class ThreadLocalTest { 13 14 public static void main(String[] args) { 15 for (int i = 0; i < 2; i++) { 16 new Thread(new Runnable() { 17 18 @Override 19 public void run() { 20 int data = new Random().nextInt(20); 21 MyThreadScopeData.getThreadInstance().setAddress( 22 "wuyidaxue" + data); 23 MyThreadScopeData.getThreadInstance().setAge(data); 24 new A().get(); 25 new B().get(); 26 } 27 }).start(); 28 } 29 } 30 31 static class A { 32 33 public void get() { 34 MyThreadScopeData myData = MyThreadScopeData.getThreadInstance(); 35 System.out.println("A from " + Thread.currentThread().getName() 36 + " getMyData: " + myData.getAddress() + "," 37 + myData.getAge()); 38 } 39 40 } 41 42 static class B { 43 44 public void get() { 45 46 MyThreadScopeData myData = MyThreadScopeData.getThreadInstance(); 47 System.out.println("B from " + Thread.currentThread().getName() 48 + " getMyData: " + myData.getAddress() + "," 49 + myData.getAge()); 50 51 } 52 } 53 } 54 55 class MyThreadScopeData { 56 57 private MyThreadScopeData() { 58 } 59 60 public static MyThreadScopeData getThreadInstance() { 61 MyThreadScopeData instance = map.get(); 62 if (instance == null) { 63 instance = new MyThreadScopeData(); 64 map.set(instance); 65 } 66 return instance; 67 68 } 69 70 private static ThreadLocal<MyThreadScopeData> map = new ThreadLocal<MyThreadScopeData>(); 71 72 private String address; 73 74 public String getAddress() { 75 return address; 76 } 77 78 public void setAddress(String address) { 79 this.address = address; 80 } 81 82 public int getAge() { 83 return age; 84 } 85 86 public void setAge(int age) { 87 this.age = age; 88 } 89 90 private int age; 91 }