package com.qimh.test;public class ThreadLocalDemo { ThreadLocallongLocal = new ThreadLocal (); ThreadLocal stringLocal = new ThreadLocal (); ThreadLocal startTime = new ThreadLocal (); ThreadLocal endTime = new ThreadLocal (); //普通变量值,会被修改 //String str = ""; ThreadLocal str = new ThreadLocal (); public void set() { longLocal.set(Thread.currentThread().getId()); stringLocal.set(Thread.currentThread().getName()); startTime.set(System.currentTimeMillis()); //str = Thread.currentThread().getName(); str.set(Thread.currentThread().getName()); } public long getLong() { return longLocal.get(); } public String getString() { return stringLocal.get(); } public long getStartTime(){ return startTime.get(); } public static void main(String[] args) throws InterruptedException { final ThreadLocalDemo test = new ThreadLocalDemo(); test.set(); System.out.println(test.getLong()); System.out.println(test.getString()); System.out.println(test.getStartTime()); System.out.println("str:" +test.str); Thread thread1 = new Thread(){ public void run() { test.set(); System.out.println(test.getLong()); System.out.println(test.getString()); System.out.println(test.getStartTime()); System.out.println((System.currentTimeMillis() - test.getStartTime() + "ms")); try { sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }; }; thread1.start(); thread1.join(); System.out.println(test.getLong()); System.out.println(test.getString()); System.out.println((System.currentTimeMillis() - test.getStartTime() + "ms")); System.out.println("str:" +test.str); }}
参考链接:https://www.cnblogs.com/dolphin0520/p/3920407.html