ThreadLocal简析-高并发

ThreadLocal 线程局部变量

ThreadLocal就是用空间换时间,synchronized是用时间换空间

比如在hibernate中session就是存在于Thread中,避免synchronized的使用,提高了效率

1.

package threadlocal_test;

import java.util.concurrent.TimeUnit;

public class ThreadLocal1 {
	volatile static Person p = new Person(); //volatile
	public static void main(String[] args) {
		new Thread(()->{
			try {
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(p.name);
		}).start();
		
		new Thread(()->{
			try {
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			p.name = "lisi";
		}).start();
	}
}

class Person{
	String name = "zhangsan";
}

 

2. 

package threadlocal_test;

import java.util.concurrent.TimeUnit;

public class ThreadLocal2 {
//	volatile static Person p = new Person(); //volatile
	static ThreadLocal tl = new ThreadLocal<>(); //ThreadLocal
	 
	public static void main(String[] args) {
		new Thread(()->{
			try {
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			System.out.println(tl.get()); //get()
		}).start();
		
		new Thread(()->{
			try {
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			tl.set(new Person());
		}).start();
	}
}

使用threadLocal内存泄漏解决

tl.remove(); //不要忘了!

参考地址:http://www.importnew.com/22039.html

你可能感兴趣的:(Java)