java ThreadLocal例子

java ThreadLocal例子


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();
	}
}



参考: http://www.cnblogs.com/dreamroute/p/5034726.html
参考: http://blog.csdn.net/lufeng20/article/details/24314381

猜你喜欢

转载自huangyongxing310.iteye.com/blog/2345075