我什么时候应该使用ThreadLocal https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html多变的?
它是如何使用的?
一种可能(也是常见)的用途是当您有一些非线程安全的对象,但您想避免同步化 https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html访问该对象(我正在看着你,简单日期格式 https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html)。相反,为每个线程提供其自己的对象实例。
例如:
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);
}
}
文档 https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)