ThreadLocal is used for each thread to have its own variable, and threads are different objects
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"); // } // ①Override the initialValue() method of ThreadLocal through the anonymous inner class to specify the initial value private static ThreadLocal<ThreadLocalTestModel> seqNum = new ThreadLocal<ThreadLocalTestModel>() { public ThreadLocalTestModel initialValue() { ThreadLocalTestModel threadLocalTestModel = new ThreadLocalTestModel(); threadLocalTestModel.setTest("AAA"); return threadLocalTestModel; } }; // ②Get the next sequence value 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 threads share sn, each generating a serial number 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){ // ④ Each thread prints 3 sequence values 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(); } }
Reference: http://www.cnblogs.com/dreamroute/p/5034726.html
Reference: http://blog.csdn.net/lufeng20/article/details/24314381