ThreadLocal变量--解决变量安全问题的终极解决之道
package 多线程;
class Runner implements Runnable {
ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
if (threadLocal.get() == null) {
threadLocal.set(new Integer(0));
}
int x = (Integer) threadLocal.get();
x = x + i;
threadLocal.set(x);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "\tsum="
+ threadLocal.get());
}
}
}
把数据存储存储到threadLocal里
package 多线程;
public class ThreadLocalTest {
public static void main(String[] args) {
Runnable run = new Runner();
Thread ta = new Thread(run,"threadA");
Thread tb = new Thread(run,"threadB");
ta.start();
tb.start();
}
}
调用之后,安全输出