【发布时间】:2018-12-28 21:35:16
【问题描述】:
我对这段代码有一个奇怪的问题:
class Test {
private static boolean test = false;
public static void main(String[] args) {
new Thread(() -> {
while (true) {
if (test) {
System.out.println("Print when breakpoint here!");
test = false;
}
}
}, "Thread1").start();
new Thread(() -> {
while (true) {
System.out.println("Print always");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
test = true;
}
}, " Thread2").start();
}
}
正如我所料,由于boolean test 不是volatile,线程1 使用test 的本地缓存值,当线程2 将其更改为true 时,线程1 不会做任何事情。但是当我在System.out.println("Prints when put a breakpoint here!"); 行设置断点时,它会到达那里并打印该行!设置断点到底发生了什么?它是否强制程序直接从内存中读取变量的值?还是发生了其他事情?
【问题讨论】:
-
Breakpoint只是用来调试java应用或者类,和内存中的变量没有任何关系
-
@Deadpool 据我所知,断点通过添加一个名为
INT 3的特殊陷阱来更改代码指令。那么到底发生了什么?
标签: java multithreading debugging breakpoints