ThreadLocal原理

╰半夏微凉° 2021-09-18 07:50 467阅读 0赞

它会为每个线程设置不同的变量副本。

Java并发编程:深入剖析ThreadLocal

package com.zpc.tet.SchedulTest;

import lombok.Synchronized;

/**
 * @Author timor
 * @Date 2019/2/26
 */
public class Test {
    ThreadLocal<Long> longLocal = new ThreadLocal<Long>();
    ThreadLocal<String> stringLocal = new ThreadLocal<String>();


    public void set() {
        longLocal.set(Thread.currentThread().getId());
        stringLocal.set(Thread.currentThread().getName());
    }

    public long getLong() {
        return longLocal.get();
    }

    public String getString() {
        return stringLocal.get();
    }

    public static void main(String[] args) throws InterruptedException {
        final Test test = new Test();


        test.set();
        System.out.println(test.getLong());
        System.out.println(test.getString());


        Thread thread1 = new Thread(){
            public void run() {
                test.set();
                System.out.println("test.getLong1():"+test.getLong());
                System.out.println("test.getString1():"+test.getString());
            };
        };
        Thread thread2 = new Thread(){
            public void run() {
                test.set();
                System.out.println("test.getLong2():"+test.getLong());
                System.out.println("test.getString2():"+test.getString());
            };
        };
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();

        System.out.println(test.getLong());
        System.out.println(test.getString());
    }
}

输出

1
main
test.getLong1():12
test.getLong2():13
test.getString1():Thread-0
test.getString2():Thread-1
1
main

发表评论

表情:
评论列表 (有 0 条评论,467人围观)

还没有评论,来说两句吧...

相关阅读