使用ThreadLocal创建线程局部变

使用ThreadLocal创建线程局部变

import lombok.extern.slf4j.Slf4j;

/**
 * @author zyy43688
 * @version $Id: ThreadLocalDemo.java, v 0.1 2018年6月12日 上午11:14:24 zyy43688 Exp $
 */
@Slf4j
public class ThreadLocalDemo {
    private static ThreadLocal<String> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) throws InterruptedException {

        threadLocal.set("matrix");
        log.info("hashCode: {}, value: {}", threadLocal.hashCode(), threadLocal.get());

        // thread1
        Thread thread1 = new Thread(() -> {
            threadLocal.set("is");
            log.info("thread1 hashCode: {}, value: {}", threadLocal.hashCode(), threadLocal.get());
        });

        // thread2
        Thread thread2 = new Thread(() -> {
            threadLocal.set("a good man!");
            log.info("thread2 hashCode: {}, value: {}", threadLocal.hashCode(), threadLocal.get());
        });

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        log.info("finish");
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容