Shallow Thread Local

April 7 , 2018 _ _

15:38

local variables within a thread 

1. Its value is bound to a thread, so that the scope of use of a variable is extended to the entire thread cycle, not limited to classes and methods, a thread can bind multiple variables, but a variable can only be bound to         On a thread, its interior is a map structure (note: an important concept in java), which is stored in the form of map<current thread object, local variable>, so to take out variables, also get the object of the current thread, commonly used The methods are set(), get();

2. Because using threadlocal is equivalent to opening up an independent storage space for the current thread ,         when the program needs to take values ​​across multiple layers, this method does not need to consider the problem of value transfer between layers, as long as you get the thread that created the variable object, you can directly take the value, making the program more concise, and each thread has an independent information storage area after this method, which can effectively reduce the problems caused by variable sharing.

Please compare the following two tests

·         Observe the first test instance

· TestThreadLocal class test code

public class TestThreadLocal {
	public static ThreadLocal<String> tt=new ThreadLocal<String>();
	public static void main(String[] args) {
		tt.set("abc");
		new TestThreadLocal2().getTt();
	}
}

· TestThreadLocal2 test code

public class TestThreadLocal2 {
	public void getTt(){
		String str=new TestThreadLocal().tt.get();
		System.out.println(str);
	}
}

· Test Results

The result can be retrieved. Main is a thread, so the program runs in the main thread.

 

·         Observe the second test instance

· TestThreadLocal2 test code (TestThreadLocal does not change, so it is not written)

public class TestThreadLocal2 {
	public void getTt(){
//		String str=new TestThreadLocal().tt.get();
//		System.out.println(str);
		new Thread(new Runnable(){//Create a new thread
			@Override
			public void run() {//implement in-thread method
					String str1=new TestThreadLocal().tt.get();
					System.out.println(str1);
			}
		}).start();	
	}
}

· Test Results


Although it is stored in the main thread, the printing code is in the new thread, so it is not available


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325578407&siteId=291194637