@SuppressWarnings("unchecked")
public class ThreadLocalComplexDemo {
@SuppressWarnings("rawtypes")
private final static ThreadLocal threadLocal = new ThreadLocal();
private static Random random = new Random();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
threadLocal.set("Thread-T1");
try {
Thread.sleep(random.nextInt(1000));
System.out.println(Thread.currentThread().getName() + " " + threadLocal.get());
} catch (Exception e) {
e.printStackTrace();
}
});
Thread t2 = new Thread(() -> {
threadLocal.set("Thread-T2");
try {
Thread.sleep(random.nextInt(1000));
System.out.println(Thread.currentThread().getName() + " " + threadLocal.get());
} catch (Exception e) {
e.printStackTrace();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(Thread.currentThread().getName() + " " + threadLocal.get());
}
}
运行结果:
Thread-0 Thread-T1
Thread-1 Thread-T2
main null