pc中存放下一条指令的地址,每一个线程都有一个程序计数器
1.是线程私有的;2.不会存在内存溢出
package 虚拟机栈;
import java.util.concurrent.TimeUnit;
public class Ex01 {
public static void main(String[] args) throws InterruptedException {
f1();
}
private static void f1() throws InterruptedException {
TimeUnit.SECONDS.sleep(5);
f2();
}
private static void f2() throws InterruptedException {
TimeUnit.SECONDS.sleep(5);
f3();
}
private static void f3() throws InterruptedException {
TimeUnit.SECONDS.sleep(5);
}
}
debug:
10s:
出栈
局部变量的线程安全问题
package 虚拟机栈;
import java.util.concurrent.TimeUnit;
public class 局部变量的线程安全问题 {
public static void main(String[] args) throws InterruptedException {
f1();
StringBuilder builder=new StringBuilder();
f3(builder);
new Thread(()->{
for(int i=0;i<10;i++){
builder.append(i);
}
}).start();
System.out.println(builder);
}
static void f1() {
//builder不存在线程安全问题
StringBuilder builder=new StringBuilder();
builder.append("abc");
}
static StringBuilder f2() {
StringBuilder builder=new StringBuilder();
builder.append("abc");
return builder;
}
static void f3(StringBuilder builder) throws InterruptedException {
TimeUnit.SECONDS.sleep(3);
builder.append("abc");
}
}
栈溢出
package 虚拟机栈;
public class 栈溢出 {
static int count;
public static void main(String[] args) {
try{
f();}catch (Error e){
System.out.println(count);
e.printStackTrace();
}
}
static void f(){
f();
++count;
}
}