package Thread.threadLocal;
/*
* ThreadLocalå®ä¾
*
* 两个线ç¨äº§ççåºå·å
±äº«ä¸ä¸ªTestå®ä¾ï¼ä½æ²¡æç¸äºå¹²æ°ï¼å 为éè¿ThreadLocal为æ¯ä¸ä¸ªè¯¥åéççº¿ç¨æä¾ç¬ç«çåé坿¬ï¼èä¸ä¼å½±åå
¶ä»å
¶ä»çº¿ç¨çæå¯¹åºç坿¬
*
* å忥æºå¶ï¼éï¼ä¸æ ·ï¼ä¸ºäºè§£å³å¤çº¿ç¨è®¿é®ç¸ååéå²çªçé®é¢
* 忥ï¼ä»¥æ¶é´æ¢ç©ºé´
* ThreadLocal:ä»¥ç©ºé´æ¢æ¶é´
*
* */
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class Test {
private static final ThreadLocal threadLocal=new ThreadLocal(){
//è¿å线ç¨å±é¨åéçåå§å¼
protected DateFormat initialValue() {
// TODO Auto-generated method stub
return new SimpleDateFormat("yyyy-MM-dd");
}
};
private static ThreadLocal seqNum=new ThreadLocal(){
protected Integer initialValue() {
return 0;
}
};
//è·åä¸ä¸ä¸ªåºåå¼
public int nextSqlNum(){
seqNum.set(seqNum.get()+1);
return seqNum.get();
}
public static void main(String[] args) {
//System.out.println(threadLocal.get().format(new Date()));
Test test=new Test();
TestClient testClient=new TestClient(test);
TestClient testClient1=new TestClient(test);
testClient.start();
testClient1.start();
}
}
class TestClient extends Thread{
private Test test;
public TestClient(Test test) {
this.test=test;
}
@Override
public void run() {
//æå°åºä¸ä¸ªåºåå·
for(int i=0;i