ThreadLocal 用法

ThreadLocal用来存放变量到当前线程中,如果存放的是成员变量或临时变量,各线程值互不干扰。如果存放的是静态成员变量,还是相互干扰的,因为存的是引用。

不干扰例子:
private static final ThreadLocal<Variables> threadVariables = new ThreadLocal<Variables>();
public static Variables getVariables(){
	Variables variables = threadVariables.get();
	if(variables == null){
		variables = new Variables();
		threadVariables.set(variables);
	}
	
	return variables;
}


相互干扰例子
private static final ThreadLocal<Variables> threadVariables = new ThreadLocal<Variables>();
private static Variables example = new Variables();

public static Variables getVariables() {
	Variables variables = threadVariables.get();
	if (variables == null) {
		variables = example;
		threadVariables.set(variables);
	}

	return variables;
}

你可能感兴趣的:(threadLocal)