JAVA-ThreadLocal使用例子备忘

概念


1.以下为多线程情况下,使用ThreadLocal的例子

/**
 * 以下为多线程情况下,使用ThreadLocal的例子
 */
private static final ThreadLocal<Integer> THREAD_LOCAL_NUM = new ThreadLocal<Integer>() {
    @Override
    protected Integer initialValue() {
        return 0;
    }
};

public static void main(String[] args) {

    for (int i = 0; i < 3; i++) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                add10ByThreadLocal();
            }
        }).start();
    }
}

private static void add10ByThreadLocal() {
    for (int i = 0; i < 5; i++) {
        //从当前线程的ThreadLocal中获取默认值
        Integer n = THREAD_LOCAL_NUM.get();
        n += 1;
        //往当前线程的ThreadLocal中设置值
        THREAD_LOCAL_NUM.set(n);
        System.out.println(Thread.currentThread().getName() + " : ThreadLocal num=" + n);
    }
}

2.以下为多线程情况下,不使用ThreadLocal的例子

/**
 * 以下为多线程情况下,不使用ThreadLocal的例子
 */
private static Integer number = 1;

public static void main(String[] args) {

    for (int i = 0; i < 3; i++) {
        new Thread(()->{
            add10ByThreadLocal();
        }).start();
    }
}

private static void add10ByThreadLocal() {
    for (int i = 0; i < 5; i++) {
        //从当前线程的ThreadLocal中获取默认值
        Integer n = number;
        number += 1;
        System.out.println(Thread.currentThread().getName() + " : ThreadLocal num=" + n);
    }
}
经验分享 程序员 微信小程序 职场和发展