content: ThreadLocal: allows us to create variables that can only be read and written by the same thread, such as a web app that moves a variable from the front to the background, and needs to always be available at any time in the thread of the request. The internal implementation is implemented through a THREADLOCALMAP map structure that takes the thread object as a key and a variable copy as value.
public class Testthreadlocal {public static class MyRunnable1 implements Runnable {private threadlocal<integer> THR eadlocal = new Threadlocal<integer> (), @Overridepublic Void Run () {Threadlocal.set (New Random (). Nextint ()); try {Thread.Sleep (2000);} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread () + ":" + threadlocal.get ());}} public static void Main (string[] args) {System.out.println ("start"); MyRunnable1 runnable = new MyRunnable1 (); Thread thread1 = new Thread (runnable); Thread thread2 = new Thread (runnable); Thread1.start (); Thread2.start ();}}
A simple example of java-threadlocal