java多线程学习5,ThreadLocal

来源:互联网 发布:诺一网络水军 编辑:程序博客网 时间:2024/04/16 12:56

示例代码

public class ThreadLocalTest {private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {@Overrideprotected Integer initialValue() {return 0;}};public ThreadLocal<Integer> geThreadLocal() {return threadLocal;}public Integer get() {geThreadLocal().set(geThreadLocal().get() + 1);return geThreadLocal().get();}public static void main(String[] args) {ThreadLocalTest tlt = new ThreadLocalTest();TestClass tc1 = new TestClass(tlt);TestClass tc2 = new TestClass(tlt);TestClass tc3 = new TestClass(tlt);tc1.start();tc2.start();tc3.start();}}class TestClass extends Thread {ThreadLocalTest thread;public TestClass(ThreadLocalTest thread) {this.thread = thread;}@Overridepublic void run() {super.run();for (int i = 0; i < 3; i++) {System.out.println("当前线程" + Thread.currentThread().getName() + "的值" + thread.get());}thread.geThreadLocal().remove();// 加快内存回收速度}}
运行结果

当前线程Thread-1的值1
当前线程Thread-2的值1
当前线程Thread-0的值1
当前线程Thread-2的值2
当前线程Thread-1的值2
当前线程Thread-2的值3
当前线程Thread-0的值2
当前线程Thread-0的值3
当前线程Thread-1的值3

0 0
原创粉丝点击