java ThreadLocal例子

[b]java ThreadLocal例子[/b]


ThreadLocal就是用于每个线程拥有自己的一份变量,线程之间是不同的对象


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;


public class ThreadLocalTest {

// private static ThreadLocalTestModel threadLocalTestModel;
//
// static {
// System.out.println("threadLocalTestModel");
// threadLocalTestModel = new ThreadLocalTestModel();
// threadLocalTestModel.setTest("AAA");
// }

// ①通过匿名内部类覆盖ThreadLocal的initialValue()方法,指定初始值
private static ThreadLocal<ThreadLocalTestModel> seqNum = new ThreadLocal<ThreadLocalTestModel>() {
public ThreadLocalTestModel initialValue() {
ThreadLocalTestModel threadLocalTestModel = new ThreadLocalTestModel();
threadLocalTestModel.setTest("AAA");
return threadLocalTestModel;
}
};

// ②获取下一个序列值
public ThreadLocalTestModel getNextNum() {
ThreadLocalTestModel threadLocalTestModel = seqNum.get();

// ThreadLocalTestModel threadLocalTestModel2 = new ThreadLocalTestModel();
// threadLocalTestModel2.setTest("BBB");
seqNum.set(threadLocalTestModel);
return threadLocalTestModel;
}

public static void main(String[] args) {
ThreadLocalTest sn = new ThreadLocalTest();
// ③ 3个线程共享sn,各自产生序列号
TestClient t1 = new TestClient(sn);
TestClient t2 = new TestClient(sn);
TestClient t3 = new TestClient(sn);
t1.start();
t2.start();
t3.start();
}

private static class TestClient extends Thread {
private ThreadLocalTest sn;

public TestClient(ThreadLocalTest sn) {
this.sn = sn;
}

public void run() {
for (int i = 0; i < 3; i++) {
ThreadLocalTestModel threadLocalTestModel = sn.getNextNum();

if(threadLocalTestModel!=null){

// ④每个线程打出3个序列值
System.out.println("thread[" + Thread.currentThread().getName() + "] --> sn[" + threadLocalTestModel.toString() + "] ,hashCode == " + threadLocalTestModel.hashCode());
threadLocalTestModel.setTest("ccC");
}
}
}
}
}



private static ThreadLocal<HttpServletRequest> reqLocal = new ThreadLocal<HttpServletRequest>();
private static ThreadLocal<HttpServletResponse> responseLocal = new ThreadLocal<HttpServletResponse>();
public static void setHttpServletRequest(HttpServletRequest request) {
reqLocal.set(request);
}
public static void clearHttpReqResponse() {
reqLocal.remove();
responseLocal.remove();
}
public static HttpServletRequest getHttpServletRequest() {
return reqLocal.get();
}
}



参考:[url]http://www.cnblogs.com/dreamroute/p/5034726.html[/url]
参考:[url]http://blog.csdn.net/lufeng20/article/details/24314381[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值