Java多线程--ThreadLocal(二)

2014-11-24 02:29:10 · 作者: · 浏览: 2
static ThreadLocal threadLocal = new ThreadLocal<>(); // 实现线程范围内共享的核心代码 public static ThreadLocalData getThreadInstance() { ThreadLocalData instance = threadLocal.get(); if (instance == null) { instance = new ThreadLocalData(); threadLocal.set(instance); } return instance; } public ThreadLocalData(String name, int id) { this.name = name; this.id = id; } public String getName() {return name;} public void setName(String name) {this.name = name;} public int getId() {return id;} public void setId(int id) {this.id = id;} @Override public String toString() { return "ThreadLocalData [name=" + name + ", id=" + id + "]"; } } 【貌似袁老师将数据进一步封装了,嗯,有点面向对象的意思,还用到了单例设计模式,乍看起来是有那么一点点功底】 【当然封装后调用起来更方便了,接下来袁老师在黑板找了个角落画出改变的调用代码】
Main方法有点小改变:
local.set(data);
// 改为
ThreadLocalData.getThreadInstance().setId(data);
ThreadLocalData.getThreadInstance()
	.setName("ysjian" + data);
A、B、C类中的getData()方法有点小改变:
System.out.println("A-->" + Thread.currentThread().getName()
	+ "-->get data-->" + local.get());
// 改为
System.out.println("A-->" + Thread.currentThread().getName()
	+ "get data-->" + ThreadLocalData.getThreadInstance());
【大概十秒钟,袁老师全身颤抖,被外面的雷声吓到,快下雨了,赶紧回家吃饭,悄悄地,袁老师走出教室,留下了黑板的涂鸦...】