ThreadLocal

简介

让每个线程都拥有自己的专属本地变量

示例

package thread;

import java.text.SimpleDateFormat;
import java.util.Random;

public class ThreadLocalExample implements Runnable{
    private static final ThreadLocal<SimpleDateFormat> formatter = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMdd HHmm"));

    @Override
    public void run() {
        System.out.println("Thread Name:" + Thread.currentThread().getName() + ", default Formatter:" + formatter.get().toPattern());
        try {
            Thread.sleep(new Random().nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        formatter.set(new SimpleDateFormat("yy MM dd"));
        System.out.println("Thread Name:" + Thread.currentThread().getName() + ", default Formatter:" + formatter.get().toPattern());
    }

    public static void main(String[] args) {
        ThreadLocalExample threadLocalExample = new ThreadLocalExample();
        for (int i = 0; i < 10; ++i) {
            Thread thread = new Thread(threadLocalExample, "" + i);
            try {
                int tmp = new Random().nextInt(1000);
                Thread.sleep(tmp);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            thread.start();
        }
    }
}

运行

Thread Name:0, default Formatter:yyyyMMdd HHmm
Thread Name:1, default Formatter:yyyyMMdd HHmm
Thread Name:2, default Formatter:yyyyMMdd HHmm
Thread Name:1, default Formatter:yy MM dd
Thread Name:2, default Formatter:yy MM dd
Thread Name:3, default Formatter:yyyyMMdd HHmm
Thread Name:0, default Formatter:yy MM dd
Thread Name:3, default Formatter:yy MM dd
Thread Name:4, default Formatter:yyyyMMdd HHmm
Thread Name:5, default Formatter:yyyyMMdd HHmm
Thread Name:4, default Formatter:yy MM dd
Thread Name:5, default Formatter:yy MM dd
Thread Name:6, default Formatter:yyyyMMdd HHmm
Thread Name:6, default Formatter:yy MM dd
Thread Name:7, default Formatter:yyyyMMdd HHmm
Thread Name:8, default Formatter:yyyyMMdd HHmm
Thread Name:7, default Formatter:yy MM dd
Thread Name:8, default Formatter:yy MM dd
Thread Name:9, default Formatter:yyyyMMdd HHmm
Thread Name:9, default Formatter:yy MM dd

分析

从结果看虽然其他的线程已经改变了formatter变量,但是运行本线程时还是原始的值。

 

posted @ 2019-06-18 15:39  jihite  阅读(293)  评论(0编辑  收藏  举报