Home  >  Article  >  Java  >  ThreadLocal solves examples of multi-threaded programs

ThreadLocal solves examples of multi-threaded programs

零下一度
零下一度Original
2017-07-26 16:52:431961browse

I believe readers have also read a lot of information about ThreadLocal on the Internet. Many blogs say this: ThreadLocal provides a new way of thinking to solve the concurrency problem of multi-threaded programs. ;The purpose of ThreadLocal is to solve the sharing problem when multiple threads access resources. If you think so, then give you 10 seconds to clear your previous misunderstandings about ThreadLocal!
Look at how the source code in JDK is written:

This class provides thread-local variables. These variables differ from
their normal counterparts in that each thread that accesses one (via its
{@code get} or {@code set} method) has its own, independently initialized
copy of the variable. {@code ThreadLocal} instances are typically private
static fields in classes that wish to associate state with a thread (e.g.,
a user ID or Transaction ID).

The translation is probably like this (English is not good, if you have a better translation, please leave a message):

The ThreadLocal class is used to provide local variables within the thread. When this kind of variable is accessed in a multi-threaded environment (accessed through the get or set method), it can ensure that the variables in each thread are relatively independent of the variables in other threads. ThreadLocal instances are usually of private static type and are used to associate threads and thread contexts.

can be summarized in one sentence: The function of ThreadLocal is to provide local variables within the thread. This type of variable works during the life cycle of the thread, reducing some common variables between multiple functions or components in the same thread. The complexity of the transfer.
For example, when I go out, I need to take the bus first and then the subway. Taking the bus and taking the subway here are like two functions in the same thread. I am a thread. I need to complete both functions. The same thing: bus card (Beijing buses and subways use bus cards), then in order not to pass the bus card variable to both functions (equivalent to not always carrying the bus card on the road), I can do this: The bus card is given to an agency in advance, and when I need to swipe the card, I ask for the bus card from this agency (of course I get the same bus card every time). In this way, as long as I (the same thread) need a bus card, I can ask this organization for it anytime and anywhere.

Someone wants to say: You can set the bus card as a global variable, so you can get the bus card anytime and anywhere, right? But what if there are many individuals (many threads)? Everyone can't all use the same bus card (we assume that the bus card is authenticated by real name), otherwise it will be confusing. Do you understand now? This is the original intention of ThreadLocal's design: to provide local variables inside the thread, which can be accessed anytime and anywhere within this thread, while isolating other threads.

(1) ThreadContext8742468051c85b06f0a0af9e3e506b5c provides a method for binding and unbinding objects for the current thread based on key/value pairs.

This class provides thread local variables. These variables are different from ordinary variables because each thread that accesses a thread (through its get or set method) has its own copy of the independently initialized variable.

ThreadLocal instances are typically private static fields in classes that wish to associate state with threads (for example: A user ID or transaction ID ). Each thread has an implicit reference to a copy of the thread local variable,

As long as the thread is alive, the ThreadLocal instance is accessible; after a thread dies, all copies of the thread-local instance will be garbage collected (unless other references exist).

8742468051c85b06f0a0af9e3e506b5c is the object saved in the thread. That is, a class T is a class attribute of a thread.

Commonly used methods are:

 1 public class ThreadLocal8742468051c85b06f0a0af9e3e506b5c { 2  3 //设置属性 4  5 public void set(T value) { 6 Thread t = Thread.currentThread(); 7 ThreadLocalMap map = getMap(t); 8 if (map != null) 9 map.set(this, value);10 else11 createMap(t, value);12 }13 14 //获取属性15 16 public T get() {17 Thread t = Thread.currentThread();18 ThreadLocalMap map = getMap(t);19 if (map != null) {20 ThreadLocalMap.Entry e = map.getEntry(this);21 if (e != null)22 return (T)e.value;23 }24 return setInitialValue();25 }26 27 //获取线程的 ThreadLocal.ThreadLocalMap28 29 ThreadLocalMap getMap(Thread t) {30 return t.threadLocals;31 }32 33 }34 35 //新建一个线程本地的localMap36 37 void createMap(Thread t, T firstValue) {38 t.threadLocals = new ThreadLocalMap(this, firstValue);39 }

(2) Usage example: connection and session are as follows:

 1 private static ThreadLocal2918aec6680a0636f336c3e736b1ff5a connectionHolder 2 = new ThreadLocal2918aec6680a0636f336c3e736b1ff5a() { 3 public Connection initialValue() { 4     return DriverManager.getConnection(DB_URL); 5 } 6 }; 7   8 public static Connection getConnection() { 9 return connectionHolder.get();10 }
 1 private static final ThreadLocal threadSession = new ThreadLocal(); 2   3 public static Session getSession() throws InfrastructureException { 4     Session s = (Session) threadSession.get(); 5     try { 6         if (s == null) { 7             s = getSessionFactory().openSession(); 8             threadSession.set(s); 9         }10     } catch (HibernateException ex) {11         throw new InfrastructureException(ex);12     }13     return s;14 }

The above is the detailed content of ThreadLocal solves examples of multi-threaded programs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn