public class OneThreadDemo { public static void main(String[] args) throws InterruptedException { ThreadLocalmainLocal = new ThreadLocal (); mainLocal.set(1); System.out.println(Thread.currentThread().getName() + mainLocal.get()); DemoThread t2 = new DemoThread(mainLocal, 2); DemoThread t3 = new DemoThread(mainLocal, 3); DemoThread t4 = new DemoThread(mainLocal, 4); t2.start(); t3.start(); t4.start(); Thread.sleep(1000); System.out.println(Thread.currentThread().getName() + mainLocal.get()); }}class DemoThread extends Thread { private ThreadLocal mainLocal; private Integer value; public DemoThread(ThreadLocal local, Integer value) { this.mainLocal = local; this.value = value; } @Override public void run() { mainLocal.set(value); Integer a = mainLocal.get(); System.out.println(Thread.currentThread().getName() + a); }}
在一个线程定义了变量,传递给其他线程使用,对变量做更改,其他线程对所做的更改可见,但是定义ThreadLoacl那个线程不可线。俗称的线程本地化。