java并发系列之ThreadLocal

package thread;

public class ThreadLocalDemo {
	//线程本地存储,不会被线程共享
	private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
	private int a;
	private ThreadLocal<User> threadLocalUser = new ThreadLocal<User>();
	public ThreadLocal<Integer> getThreadLocal() {
		return threadLocal;
	}

	public void setThreadLocal(ThreadLocal<Integer> threadLocal) {
		this.threadLocal = threadLocal;
	}

	public int getA() {
		return a;
	}

	public void setA(int a) {
		this.a = a;
	}

	public ThreadLocal<User> getThreadLocalUser() {
		return threadLocalUser;
	}

	public void setThreadLocalUser(ThreadLocal<User> threadLocalUser) {
		this.threadLocalUser = threadLocalUser;
	}

	
	
	
	public static void main(String[] args) throws InterruptedException {

		final ThreadLocalDemo threadLocalDemo = new ThreadLocalDemo();
		//初始化为0
		threadLocalDemo.getThreadLocal().set(0);
		
		for (int i = 0; i < 10000; i++) {
			
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					//修改普通属性
					int a = threadLocalDemo.getA();
					threadLocalDemo.setA(a+1);
					
					//修改ThreadLocal属性
					Integer i = threadLocalDemo.getThreadLocal().get();
					threadLocalDemo.getThreadLocal().set(i+1);
					
				}
			}).start();
		}
		
		Thread.sleep(1000);
		
		
		//不是一个ThreadLocal对象,不一定会输出10000
		System.err.println(threadLocalDemo.getA());
		
		
		//是一个ThreadLocal对象,会输出10000
		System.err.println(threadLocalDemo.getThreadLocal().get());
	
		
		
	}
	
}


class User{
	private int userId;
	private String username;
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	
}
发布了89 篇原创文章 · 获赞 67 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/xl_1803/article/details/100061917