源码理会

Java 中的 ThreadLocal是线程内的局部变量, 它为每个线程生存变量的一个副本。ThreadLocal 工具可以在多个线程中共享, 但每个线程只能读写个中本身的副本。

目次:

代码示例

源码理会

InheritableThreadLocal

ThreadLocalMap

Get 流程

Set 流程

Remove

代码示例

我们编写一个简朴的示例:

import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @author finley */ public class MyThread extends Thread { private static final ThreadLocal<Integer> threadLocal = new ThreadLocal<>(); private static final Random random = new Random(); @Override public void run() { int localValue = random.nextInt(); threadLocal.set(localValue); System.out.println("Thread: " + Thread.currentThread().getName() + " set thread local: " + localValue); try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread: " + Thread.currentThread().getName() + " threadLocal: " + threadLocal.get() + ", local: " + localValue); } public static void main(String[] args) { int concurrent = 10; ExecutorService service = Executors.newFixedThreadPool(concurrent); for (int i = 0; i < concurrent; i++) { service.execute(new MyThread()); } service.shutdown(); } }

运行功效:

Thread: pool-1-thread-1 set thread local: -1262320606 Thread: pool-1-thread-2 set thread local: 1222545653 Thread: pool-1-thread-3 set thread local: 2067394038 Thread: pool-1-thread-4 set thread local: 920362206 Thread: pool-1-thread-5 set thread local: -1977931750 Thread: pool-1-thread-6 set thread local: 985735150 Thread: pool-1-thread-7 set thread local: -602752866 Thread: pool-1-thread-8 set thread local: 672437027 Thread: pool-1-thread-9 set thread local: 1063652674 Thread: pool-1-thread-10 set thread local: 1790288576 Thread: pool-1-thread-1 threadLocal: -1262320606, local: -1262320606 Thread: pool-1-thread-3 threadLocal: 2067394038, local: 2067394038 Thread: pool-1-thread-4 threadLocal: 920362206, local: 920362206 Thread: pool-1-thread-6 threadLocal: 985735150, local: 985735150 Thread: pool-1-thread-7 threadLocal: -602752866, local: -602752866 Thread: pool-1-thread-2 threadLocal: 1222545653, local: 1222545653 Thread: pool-1-thread-5 threadLocal: -1977931750, local: -1977931750 Thread: pool-1-thread-8 threadLocal: 672437027, local: 672437027 Thread: pool-1-thread-10 threadLocal: 1790288576, local: 1790288576 Thread: pool-1-thread-9 threadLocal: 1063652674, local: 1063652674

可以看到10个线程挪用同一个ThreadLocal工具的set要领写入随机值, 然后读取到本身写入的副本。

源码理会

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wsdjxw.html