`
bjmike
  • 浏览: 277249 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

 
阅读更多
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()方法内的变量在各个线程之间是公用的数据。
分享到:
评论
3 楼 jaedong 2012-01-12  
不如果想要这种结果只能让第一个线程制行完
td1Session is null
id=1
1
1
td2Session is null
id=2
2
2


加了synchronized还是你上边的结果,主要还是AotmicLong是全局类型.
2 楼 bjmike 2012-01-12  
jaedong 写道
AtomicLong是static类型的,加了synchronized还是这种效果

我以前测过,是在getSession上进行同步控制,你可以测试一下,如果我没记错的话,效果是不一样的。
1 楼 jaedong 2012-01-12  
AtomicLong是static类型的,加了synchronized还是这种效果

相关推荐

Global site tag (gtag.js) - Google Analytics