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;
	}
	
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章