运行代码
public class ThreadLocalTest {
public static class MyRunnable implements Runnable {
@Override
public void run() {
ThreadLocalTest.test();
}
}
public static void main(String[] args) {
MyRunnable sharedRunnableInstance = new MyRunnable();
Thread thread1 = new Thread(sharedRunnableInstance);
Thread thread2 = new Thread(sharedRunnableInstance);
thread1.start();
thread1.run();
thread1.run();
thread2.start();
thread2.run();
}
private static ThreadLocal threadLocal = new ThreadLocal();
private static void test() {
if (threadLocal.get() == null) {
threadLocal.set(Thread.currentThread().getName() + (Math.random() * 100D));
}
System.out.println(threadLocal.get());
}
}
多次运行返回结果
main22.761071473890006
main22.761071473890006
Thread-056.212406593371476
main22.761071473890006
Thread-113.707351108894805
结果分析:同一个线程取出来的值是相同的,而且在多个线程运行过程中不会覆盖其他线程存放的数据
表明,ThreadLocal,它是线程绑定的变量,提供线程局部变量(一个线程一个ThreadLocal,A线程的ThreadLocal只能看到A线程的ThreadLocal,不能看到B线程的ThreadLocal)
哈哈哈
网友评论