我用Java编写的一些代码有一个有趣的问题。我正在使用jdk-17.0.1在eclipse的最新版本中执行这段代码。代码的目的是每隔几毫秒拍摄一次屏幕截图,但前提是运行为真。一开始,跑步是错误的。我可以按下一定的键,使跑步成为真实。这是代码
double timePerTick = 1_000_000_000/fps;
double delta = 0;
long now;
long lastTime = System.nanoTime();
while (true) {
now = System.nanoTime();
delta+= (now-lastTime)/timePerTick;
lastTime = now;
if (delta >= 1) {
//for some reason code only works if this print statement here
//System.out.println("WOWEE");
if (running) {
//Create rectangle screen-capture around cursor
BufferedImage image = robot.createScreenCapture(new Rectangle(0,0, width, height));
try {
output.write(("Capture taken \n").getBytes());
System.out.println("WRITTEN!");
} catch (IOException e1) {
// TODO Auto-generated catch block
System.out.println("BRUH!");
e1.printStackTrace();
}
}
delta--;
}
} 问题是,if (正在运行)语句永远不会运行,即使在运行为true时也是如此。但是,当我在if(增量)代码之后取消对System.out.println语句的注释时,它运行得非常好。如下所示:
double timePerTick = 1_000_000_000/fps;
double delta = 0;
long now;
long lastTime = System.nanoTime();
while (true) {
now = System.nanoTime();
delta+= (now-lastTime)/timePerTick;
lastTime = now;
if (delta >= 1) {
//for some reason code only works if this print statement here
System.out.println("WOWEE");
if (running) {
//Create rectangle screen-capture around cursor
BufferedImage image = robot.createScreenCapture(new Rectangle(0,0, width, height));
try {
output.write(("Capture taken \n").getBytes());
System.out.println("WRITTEN!");
} catch (IOException e1) {
// TODO Auto-generated catch block
System.out.println("BRUH!");
e1.printStackTrace();
}
}
delta--;
}
} 在第一个代码中,没有任何东西被打印出来,但是在第二个代码中,WOWEE被一次又一次地打印出来。顺便说一句,如果一开始运行是真的话,那么这两个代码都可以正常工作。但是,如果您从but = false切换到but= true,第一段代码将不会输出任何内容,但是第二段代码将从不打印到打印WOWEE。有什么原因吗?
顺便说一下,如果输出是必要的信息,那么输出就是一个FileOutputStream实例。
发布于 2022-01-31 05:17:03
user16320675在评论中找到了我问题的答案,但出于某种原因,他们删除了他们的评论。我等着看他们是否会回来,但他们没有回来。所以,我会把他们给我的信息发出去。我的程序不能工作的原因是,变量“运行”被多个线程访问,其中一个线程是主线程,另一个线程是监视键盘输入的线程。当多个线程访问一块内存时,必须将其声明为“易失性”,以确保同步问题不会发生。像这样
public static volatile boolean running;https://stackoverflow.com/questions/70919025
复制相似问题