同一代码多线程并发的混乱情况

public class Thread1 extends Thread {
	private static final ThreadLocal<Session> threadSession = new ThreadLocal<Session>();

	public static Session getSession() {
		Session s = threadSession.get();
		if (s == null) {
			System.out.println("s==null");
			s = new Session();
			threadSession.set(s);

		} else {
			System.out.println(s.getId());
		}
		return s;
	}

	public void run() {
		for (int i = 0; i < 3; i++) {
			Session s = getSession();
		}
	}

}


public class ThreadLocalTest {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Thread1 t1=new Thread1();
		Thread1 t2=new Thread1();
		
		try {
			t1.start();
			//t1.join();
			t2.start();
			//t2.join();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/*t1.start();
		t2.start();*/
	}

}


public class Session {
	private static AtomicLong id=new AtomicLong(0);
	
	Session(){
		System.out.println("haha:"+id.incrementAndGet());
	}
	
	public long getId(){
		return id.get();
	}
}



打印出的结果:

s==null
s==null
haha:1
haha:2
2
2
2
2

这是什么原因造成的?分析后发现第二个线程threadSession.set(s);
时把第一个线程的session set进去了,这就说明在执行getSession()方法时,是在同一内存区操作的,若不进行同步,getSession()方法内的变量在各个线程之间是公用的数据。

你可能感兴趣的:(线程并发)