Java内存模型全称JMM(Java Memory Model)
内存主要有堆和栈组成
下面来一段demo代码详细讲解堆栈的作用,以及流程
public class Employee {private String name;private Integer age;private Department department;public Employee(){}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Department getDepartment() {return department;}public void setDepartment(Department department) {this.department = department;}public void sayJoke(String content){System.out.println(this.getName() + "说" + content);}public static void main(String[] args) {Employee emp = new Employee();emp.setName("老齐");emp.setAge(13);Department department = new Department();department.setDname("小卖部");emp.setDepartment(department);emp.sayJoke("一言不合就开车");}
}class Department{private String dname;public String getDname() {return dname;}public void setDname(String dname) {this.dname = dname;}
}
1.运行方法前进行类的加载,加载到employee和department这两个类,把这两个类的结构,成员变量和成员方法加载到方法区(方法区静态还会存储静态的方法和变量
)
2.启动main方法,创建一个线程,会开辟一个栈空间,压入mian方法的栈(栈帧:每执行一个方法就会有一个对应的栈帧
)
3.emp = new Empolyee(); 创建对象,存储在堆空间,将栈地址指向开辟的堆空间(也可以叫做引用
)
4.emp.setName(“老齐”);先在方法区创建字符串"老齐",然后将字符串引用到name属性上,setName()方法的栈帧执行完,就会出栈
5.emp.setAge(13);数字按值引用,直接赋值,不需要在静态区开辟新空间
6.dept = new Department();同上3
7.dept.setDname(“小卖铺”);同上4
8.emp.setDepartment(dept);Employee对象的department属性直接指向Department对象的地址(也可以叫做地址被属性所引用)
9.emp.sayJoke(“一言不合就开车”)
10.方法执行完成,站内栈帧全部弹出,线程销毁