request作用域的Bean、事务管理、任务调度、AOP等模块共享变量的思想及源代码的实现:
// 共享数据的公共接口
interface TopInterface {
ThreadLocal<String> threadLocal = new ThreadLocal<String>();// 三层共享的线程变量
}
class TestDao implements TopInterface {
public void save(String name) {
if(null == threadLocal.get())
threadLocal.set(name);
}
public String find() {
return threadLocal.get();
}
}
class TestServiceImpl implements TopInterface {
private TestDao dao = new TestDao();
public void save(String name) {
dao.save(name);
}
public String find() {
return threadLocal.get();
}
}
class TestActionImpl implements TopInterface {
private TestServiceImpl service = new TestServiceImpl();
public void save(String name) {
service.save(name);
}
public String find() {
return threadLocal.get();
}
}
测试代码:
public static void main(String[] args) {
TestActionImpl action = new TestActionImpl();
action.save("张三");
TestDao dao = new TestDao();
System.out.println("hello : " + dao.find() + ", 这是dao层");
TestServiceImpl service = new TestServiceImpl();
System.out.println("hello : " + service.find() + ", 这是service层");
System.out.println("hello : " + action.find() + ", 这是action层");
}
输出结果:
hello : 张三, 这是dao层
hello : 张三, 这是service层
hello : 张三, 这是action层
该变量在多线程环境下是线程安全的,其起重要的还是ThreadLocal。
1859

被折叠的 条评论
为什么被折叠?



