美文网首页
自己实现一个ThreadLocal

自己实现一个ThreadLocal

作者: 幻觉幻觉 | 来源:发表于2021-10-21 08:58 被阅读0次
public class ThreadLocalMy<T> {

    private Map<Thread, Map<ThreadLocalMy, T>> map = new ConcurrentHashMap<>();

    public T get() {
        Map<ThreadLocalMy, T> t = map.get(Thread.currentThread());
        if (t == null) {
            return null;
        }
        return t.get(this);
    }

    public void set(T value) {
        Map<ThreadLocalMy, T> t = map.get(Thread.currentThread());
        if (t == null) {
            t = new HashMap<>();
            t.put(this, value);
            map.put(Thread.currentThread(), t);
        }
        t.put(this, value);
    }

    public void remove() {
        map.remove(Thread.currentThread());
    }
}
public class ThreadTest implements Runnable {

    public static final ThreadLocalMy<Integer> tt = new ThreadLocalMy<>();
    public static AtomicInteger t2 = new AtomicInteger(0);
    public static int t3;
    public static final ThreadLocalMy<Integer> t4 = new ThreadLocalMy<>();
    @Override
    public void run() {
        for (int i=0;i<1000000; i++) {
            if (tt.get() == null) {
                tt.set(0);
            }
            tt.set(tt.get() + 1);
            t2.incrementAndGet();
            t3 = t3 + 1;
            if (t4.get() == null) {
                t4.set(0);
            }
            t4.set(t4.get() + 3);
        }
        System.out.println("threadlocaltt" + tt.get());
        System.out.println("atomic" + t2);
        System.out.println(t3);
        System.out.println("threadlocalt4" + t4.get());
    }

}

测试代码

public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new ThreadTest());

        Thread t2 = new Thread(new ThreadTest());
        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }

相关文章

网友评论

      本文标题:自己实现一个ThreadLocal

      本文链接:https://www.haomeiwen.com/subject/xdcfaltx.html