ThreadLocal 实现线程内共享变量
package com.cn.gbx; import java.util.Date; import java.util.Random; import java.util.Timer; import java.util.TimerTask; public class TestThread { static class A{ public void get() { User user = User.getInstance(); System.out.println("A from " + Thread.currentThread().getName() + " get data:" + user.getName() + " : " + user.getPassword()); } } static class B{ public void get(){ User user = User.getInstance(); System.out.println("B from " + Thread.currentThread().getName() + " get data:" + user.getName() + " : " + user.getPassword()); } } 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(); System.out.println(Thread.currentThread().getName() + " : data = " + data); User.getInstance().setName("name:" + data); User.getInstance().setPassword("p:" + data); new A().get(); new B().get(); //A,B 模块得到的都是与本线程相关联的数据, 例如数据库connection等等 } } ).start(); } } } class User{ //类似单例的懒汉模式 其实ThreadLocal 就是一个Map只不过是自动将key设为本地线程 private static ThreadLocal<User> threadLocal = new ThreadLocal<User>(); private User() {} public static User getInstance() { User user = threadLocal.get(); if (user == null) { user = new User(); threadLocal.set(user); } return user; } private String name; private String password; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } 输出: Thread-1 : data = 1362065454 Thread-0 : data = 1208952694 A from Thread-0 get data:name:1208952694 : p:1208952694 A from Thread-1 get data:name:1362065454 : p:1362065454 B from Thread-1 get data:name:1362065454 : p:1362065454 B from Thread-0 get data:name:1208952694 : p:1208952694