1.
1 public class ConnThreadLocal { 2 3 //线程变量副本,每个线程都有一个,所以多线程的时候,就不会出现覆盖.而是每个线程一个 4 public static ThreadLocal<String> th = new ThreadLocal<String>(); 5 6 public void setTh(String value){ 7 th.set(value); 8 } 9 public void getTh(){ 10 System.out.println(Thread.currentThread().getName() + ":" + this.th.get()); 11 } 12 13 public static void main(String[] args) throws InterruptedException { 14 15 final ConnThreadLocal ct = new ConnThreadLocal(); 16 Thread t1 = new Thread(new Runnable() { 17 @Override 18 public void run() { 19 ct.setTh("张三"); 20 ct.getTh(); //t1:张三 21 } 22 }, "t1"); 23 24 Thread t2 = new Thread(new Runnable() { 25 @Override 26 public void run() { 27 try { 28 Thread.sleep(1000); 29 ct.setTh("李四"); 30 ct.getTh();//t2:李四 31 } catch (InterruptedException e) { 32 e.printStackTrace(); 33 } 34 } 35 }, "t2"); 36 37 t1.start(); 38 t2.start(); 39 } 40 41 }