3、测试代码
package com.sangfor.threadlocal; public class TestThreadLocal { public static final ThreadLocal<Integer> sThreadLocal = new ThreadLocal<Integer>(){ @Override protected Integer initialValue() { return 0; } }; public static void main(String[] args) { for (int i = 0; i < 10; i++) { new MyThread(i).start(); } } static class MyThread extends Thread { public int index; public MyThread(int index) { this.index = index; } @Override public void run() { System.out.println("线程" + index + "的初始value:" + sThreadLocal.get()); for (int i = 0; i < 10; i++) { sThreadLocal.set(sThreadLocal.get() + i); } System.out.println("线程" + index + "的累加value:" + sThreadLocal.get()); } } }
4、运行结果
线程0的初始value:0 线程0的累加value:45 线程1的初始value:0 线程1的累加value:45 线程2的初始value:0 线程2的累加value:45 线程3的初始value:0 线程3的累加value:45 线程4的初始value:0 线程4的累加value:45 线程5的初始value:0 线程5的累加value:45 线程6的初始value:0 线程7的初始value:0 线程7的累加value:45 线程6的累加value:45 线程8的初始value:0 线程8的累加value:45 线程9的初始value:0 线程9的累加value:45
5、总结
用ThreadLocal修饰的变量,感觉就是每个线程都拥有一份原始数据的拷贝,每个线程只能修改自己的数据,其它线程不可以修改