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


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()方法内的变量在各个线程之间是公用的数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值