WEB开发网
开发学院软件开发Java Java线程:深入ThreadLocal 阅读

Java线程:深入ThreadLocal

 2010-01-22 00:00:00 来源:WEB开发网   
核心提示: 然后运行测试:Thread-21Thread-22Thread-14Thread-16Thread-33Thread-39Thread-310Thread-18Thread-07Thread-011Thread-012Thread-25Processfinishedwithexitcode0从这

然后运行测试:

Thread-2  1 
Thread-2  2 
Thread-1  4 
Thread-1  6 
Thread-3  3 
Thread-3  9 
Thread-3  10 
Thread-1  8 
Thread-0  7 
Thread-0  11 
Thread-0  12 
Thread-2  5 
Process finished with exit code 0

从这里可以看出,四个线程共享了tlt变量,结果每个线程都直接修改tlt的属性。

三、自己实现个ThreadLocal

package com.lavasoft.test2; 
import java.util.Collections; 
import java.util.HashMap; 
import java.util.Map; 
/** 
* 使用了ThreadLocal的类 
* 
* @author leizhimin 2010-1-5 10:35:27 
*/ 
public class MyThreadLocal { 
        //定义了一个ThreadLocal变量,用来保存int或Integer数据 
        private com.lavasoft.test2.ThreadLocal<Integer> tl = new com.lavasoft.test2.ThreadLocal<Integer>() { 
                @Override 
                protected Integer initialValue() { 
                        return 0; 
                } 
        }; 
        public Integer getNextNum() { 
                //将tl的值获取后加1,并更新设置t1的值 
                tl.set(tl.get() + 1); 
                return tl.get(); 
        } 
} 
class ThreadLocal<T> { 
        private Map<Thread, T> map = Collections.synchronizedMap(new HashMap<Thread, T>()); 
        public ThreadLocal() { 
        } 
        protected T initialValue() { 
                return null; 
        } 
        public T get() { 
                Thread t = Thread.currentThread(); 
                T obj = map.get(t); 
                if (obj == null && !map.containsKey(t)) { 
                        obj = initialValue(); 
                        map.put(t, obj); 
                } 
                return obj; 
        } 
        public void set(T value) { 
                map.put(Thread.currentThread(), value); 
        } 
        public void remove() { 
                map.remove(Thread.currentThread()); 
        } 
}

上一页  1 2 3 4 5 6 7  下一页

Tags:Java 线程 深入

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接