java - System.out.println("") 改变程序的行为
问题描述
我有以下代码:
boolean running = true;
while (running) {
MathStackJPanel focused = Main.frame.mainPanel.focused;
//System.out.print("");
if (focused != null) {
Point p = focused.getMousePosition();
ExpressionComponent ep = focused.getUnderPoint(p);
}
}
focused.getUnderPoint(p)
应该打印一些东西(用于调试)但没有。一旦我取消注释System.out.print("")
,代码就会按预期工作,并且我会看到控制台中打印的内容(来自focused.getUnderPoint(p)
)。为什么那条应该什么都不做的简单行会完全修改我的代码的行为?另外,我可以说 while 循环内的代码根本没有运行,因为System.out.print("")
在某些情况下,当我取消注释时,会抛出异常(如预期的那样)。
java是否优化了我的while循环,即使它不应该?
有人要求一个更好的例子:
public static Object b = null;
public static void a() {
System.out.println("OK");
}
public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
b = 4;
});
thread.start();
while (true) {
//System.out.print("");
if (b != null) {
a();
}
}
}
取消注释该行以使其工作(打印正常)
解决方案
推荐阅读
- anglesharp - AngleSharp OpenAsync 返回令人困惑的错误?没有网络的时候
- sql-server - 使用 Azure Active Directory 连接到 MSSQL 服务器的 JDBC
- java - 如何在 java 中将 SSL 客户端证书与 jersey 客户端一起使用
- botium-box - Botium:- 使用 botium 和 webdriverIO 进行聊天机器人测试
- c++ - 如何控制从 long 到 int 的隐式转换?
- php - 如何在 HEREDOC 字符串“HTML 代码”块中输出 PHP 函数
- android - 撰写导航 - 替换起始路线并清除返回堆栈
- keycloak - 通过 keycloak API 访问应用程序
- vue.js - 为什么路由器链接在 App.vue 中工作但在组件中给我“无法解析组件:路由器链接”?
- reactjs - RTK Query 会默认存储所有数据吗?