JVM在执行一个方法时会隐含着添加一个变量,用于记录方法的返回值。
* 该变量的类型取决于方法返回值的声明类型
* 并在方法执行完毕后将该变量的值返回
public static int dosome() {
int x = 1;
try {
return x;
} finally {
x++; //x的改变并不会影响返回值的变量——return的值
System.out.println("finally" + x);
}
}
public static void main(String[] args) {
int num = dosome();
System.out.println(num);
}
即使finally之前执行过return,最终返回的还是finally中的return
public static int test(String str) {
try {
return str.charAt(0);
} catch (NullPointerException e) {
return 1;
} catch (RuntimeException e) {
return 2;
} finally {
//实际开发中不应当在finally中return的
return 3;
}
}
public static void main(String[] args) {
System.out.println(
test("0") + "," + test(null) + "," + test("")
);
}
经常被大量的读取,很少进行更新操作的 会使用缓存,在new对象或调用API时会同步内存
public class VolatileDemo {
/**
* volatile 关键字
* 用于让多个cpu执行时强制访问内存中的a,而不能每个CUP都将其复制到缓冲中执行,
* 该关键字用于修饰一个属性,一般用于基本类型的属性使用
* 否则会出现并发修改不可见的情况,
*/
private int a = 1;
// private volatile int a = 1;
public static void main(String[] args) {
VolatileDemo demo = new VolatileDemo();
Thread t = new Thread(()->{
System.out.println("线程开始了...");
while (demo.a==1);
System.out.println("线程结束了...");
});
t.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
demo.a=2;
System.out.println("主线程将demo.a的值改成了:"+demo.a);
}
}