ThreadLocal

ThreadLocal

MyThread:

package com.itheima.threadlocal;

public class MyThread extends Thread{

	private ThreadLocal tl;

	public MyThread(ThreadLocal tl) {
		this.tl = tl;
	}

	@Override
	public void run() {
		System.out.println(tl.get()+"aaaaaaaaaaaa");  
	}
	
}
TestThreadLocal:

package com.itheima.threadlocal;

public class TestThreadLocal {
	public static void main(String[] args) {
		ThreadLocal tl = new ThreadLocal(); //当前线程
		tl.set("p");
		
		MyThread mt = new MyThread(tl); //开启了一个新的线程
		mt.start();
		
		System.out.println(tl.get());  //取不出来

	}
}
模拟ThreadLocal的设计:
public class ThreadLocal{
	private Map container = new HashMap();
	public void set(Object value){
		container.put(Thread.currentThread(),value);//用当前线程作为key
	}
	public Object get(){
		return container.get(Thread.currentThread());
	}
	public void remove(){
		container.remove(Thread.currentThread());
	}
}
总结:调用该类的get方法,永远返回当前线程放入的数据。线程局部变量
把当前线程的东西存入ThreadLocal中,其他线程就访问不到,保证线程安全

你可能感兴趣的:(JavaWeb)