|
Usage
The easiest way to call multiple threads in the same process, there will be complicated by the problem, to solve this problem is to save the data in the Thread of their structure, that is the role of the ThreadLocal. Usage is as follows:
classJavaBean {staticThreadLocal < Integer > threadLocal = newThreadLocal < Integer > (); publicvoid prepare () {
threadLocal.set (0);} publicvoid work () {for (int i = 0; i <1000; i ++) {int val = threadLocal.get ();
val ++;
threadLocal.set (val);} System.out.println (threadLocal.get ());}} classWorkerextendsThread {JavaBean bean; publicWorker (JavaBean bean) {this.bean = bean;} publicvoid run () {
bean.prepare ();
bean.work ();}} publicclassThreadLocalDemo {publicstaticvoid main (String [] args) {JavaBean bean = newJavaBean (); for (int i = 0; i <100; i ++) {newWorker (bean) .start ();} }}
You can see from the output, multiple threads operating with a threadLocal, and the results can not go wrong.
ThreadLocal can be seen as a package is Thread.threadLocals Moreover, in the program is not directly accessible to Thread.threadLocals.
principle
Following is a brief look at the principle of ThreadLocal in Thread is saved in a Map, the type can be considered as Map , where T is the type of data you want to save. When removed from the data, the flow call is:
Thread.currentThread (). ThreadLocals.getEntry (threadLocal) .value
Thus, when a different thread of execution on the same threadLocal get to the different data between threads isolation through "each holding a different Map" to achieve, but the object is actually seen threadLocal KEY , before the operation is to get VALUE. In fact, do yourself a thread-safe data storage solution is also this idea.
Not an ordinary reference stored data used in ThreadLocalMap Rather, the WeakReference do:
staticclassEntryextendsWeakReference < ThreadLocal > {Object value; Entry (ThreadLocal k, Object v) {super (k);
value = v;}}
So if ThreadLocal is released, then ThreadLocalMap the Entry will be released, it will not cause a memory leak. |
|
|
|