当前位置:网站首页>线程运行原理
线程运行原理
2022-06-24 09:47:00 【兀坐晴窗独饮茶】
栈与栈帧
Java Virtual Machine Stacks (Java 虚拟机栈)
- JVM 中由堆、栈、方法区所组成,其中栈内存是给线程使用,
- 每个线程启动后,虚拟机就会为其分配一块栈内存。
- 每个栈由多个栈帧(Frame)组成,对应着每次方法调用时所占用的内存
- 每个线程只能有一个活动栈帧,对应着当前正在执行的那个方法
具体示例如下 :
package cn.knightzz.example.e2.source;
public class TestFrame {
public static void method1(int n) {
Object m = method2(n + 1);
System.out.println("m = " + m);
}
public static Object method2(Object n) {
return n;
}
public static void main(String[] args) {
method1(10);
}
}
当我们运行到主线程method1(10) 时, 可以看到只有主线程在活动

而当我运行到method2(n+1) 位置时 当前的活动栈帧对应着 method1

继续运行直到运行到 method2时可以看到此时有三个栈帧, 活动栈帧是 method2, 所以
- 每个栈由多个栈帧(Frame)组成,对应着每次方法调用时所占用的内存
- 每个线程只能有一个活动栈帧,对应着当前正在执行的那个方法

栈帧图解
代码示例
package cn.knightzz.example.e2.source;
/** * @author 王天赐 * @title: TestFrame * @projectName hm-juc-codes * @description: 线程的栈帧 * @website <a href="http://knightzz.cn/">http://knightzz.cn/</a> * @github <a href="https://github.com/knightzz1998">https://github.com/knightzz1998</a> * @create: 2022-06-15 22:18 */
public class TestFrame {
public static void method1(int n) {
Object m = method2(n + 1);
System.out.println("m = " + m);
}
public static Object method2(Object n) {
return n;
}
public static void main(String[] args) {
method1(10);
}
}
初始状态如下 :
- 所有的代码加载进方法区, JVM虚拟机为主程序分配栈内存

执行主方法, 创建 main栈帧

局部变量表 :
- 存储局部变量以及方法参数, 对于main函数来说, 局部变量表存储的就是
args args存储的是执行程序的命令信息 :java -jar -Xmx2G后面的参数信息
继续向下执行, 执行到 method1 方法内是 , 此时注意 :
- 程序计数器里记录了此时程序的位置 :
method1(10), 随着继续向下执行, 程序计数器会记录执行的每一行代码 - 返回地址指向方法区里
main函数位置的method1(10)位置 - 局部变量存储了
n和m两个变量, 一个是方法输入参数, 一个是对象 - 注意 : 对象是存储在堆中的

当我们继续向下执行时, 执行到 method2 :
- 返回地址指向
method1中调用method2的位置

当最后一个方法 method2 执行结束后, 会根据返回地址逐步返回, 直到结束
边栏推荐
- 机器学习——感知机及K近邻
- 小程序 rich-text中图片点击放大与自适应大小问题
- leetCode-面试题 01.05: 一次编辑
- Juul, the American e-cigarette giant, suffered a disaster, and all products were forced off the shelves
- Machine learning perceptron and k-nearest neighbor
- Practice sharing of packet capturing tool Charles
- 3.员工的增删改查
- 2.登陆退出功能开发
- tf.errors
- SVG+js拖拽滑块圆形进度条
猜你喜欢
随机推荐
Troubleshooting steps for Oracle pool connection request timeout
Distributed | how to make "secret calls" with dble
Caching mechanism for wrapper types
Uniapp develops a wechat applet to display the map function, and click it to open Gaode or Tencent map.
Image click enlargement and adaptive size in the applet rich text
leetCode-面试题 16.06: 最小差
机器学习——主成分分析(PCA)
Leetcode-498: diagonal traversal
Resolved: methods with the same name as their class will not be constructors in
5.菜品管理业务开发
牛客-TOP101-BM28
上升的气泡canvas破碎动画js特效
Uniapp develops wechat official account, and the drop-down box selects the first one in the list by default
JMeter接口测试工具基础— 取样器sampler(二)
[resource sharing] 2022 International Conference on Environmental Engineering and Biotechnology (coeeb 2022)
Leetcode - 498: traversée diagonale
leetCode-2221: 数组的三角和
SSM integration
Record the range of data that MySQL update will lock
24. 图像拼接大作业









