今天在看深入理解java虚拟机时看到一段话,大意是说JMM模型不会对局部变量及方法参数实施内存一致性协议的约定,方法参数好说,因为是线程栈内部的数据,是线程私有的,但是局部变量如果是对象呢,线程持有的是对象的引用,如果多个线程同时对对象修改呢?为此特意做了个实验:
Thread hello = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
Student student = new Student();
student.setName("hello");
System.out.println("hello:" + student);
}
});
Thread world = new Thread(new Runnable() {
@Override
public void run() {
Student student = new Student();
student.setName("world");
System.out.println("world:" + student);
}
});
hello.start();
world.start();
结果输出:
world:oa.demo.thread.ObjectTest.Student@33c5a8a9
hello:oa.demo.thread.ObjectTest.Student@5a6b83b0
可以发现,其实每个线程内部的对象都在堆中创建了一份,并不共用,所以并发不存在问题