ThreadLocal
2018-07-04 本文已影响0人
yxuiang
运行代码
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