何时以及如何使用 ThreadLocal 变量? [英] When and how should I use a ThreadLocal variable?

查看:29
本文介绍了何时以及如何使用 ThreadLocal 变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我什么时候应该使用 ThreadLocal 变量?

When should I use a ThreadLocal variable?

如何使用?

推荐答案

一种可能(且常见)的用途是当您有一些不是线程安全的对象,但您想避免 同步对该对象的访问(我在看着你,SimpleDateFormat).相反,为每个线程提供自己的对象实例.

One possible (and common) use is when you have some object that is not thread-safe, but you want to avoid synchronizing access to that object (I'm looking at you, SimpleDateFormat). Instead, give each thread its own instance of the object.

例如:

public class Foo
{
    // SimpleDateFormat is not thread-safe, so give one to each thread
    private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){
        @Override
        protected SimpleDateFormat initialValue()
        {
            return new SimpleDateFormat("yyyyMMdd HHmm");
        }
    };

    public String formatIt(Date date)
    {
        return formatter.get().format(date);
    }
}

文档.

这篇关于何时以及如何使用 ThreadLocal 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆