Java在Linux中运行时不会中断一段时间
我在作业的 Java 代码中发现了一个神秘的问题。一个朋友编写了一个应用程序,该应用程序一开始是这样的:
public void run() {
vm.setVisible(true);
while(!end);
System.out.println("Finish");
vm.setVisible(false);
}
在所有执行过程中以及当用户退出应用程序时,布尔值“end”为 false,这会发生:
private class CloseSys implements ActionListener {
public CloseSys() {super();}
public void actionPerformed(ActionEvent e) {
System.out.println("CLOSE SYS");
System.out.println("end: "+end);
end = true;
System.out.println("end: "+end);
}
}
println 显示“end”的值更改为 true,并且在我朋友的逻辑中计算机(MacOS)同时完成,应用程序也完成。
问题是,在我的计算机(Ubuntu Linux)中, println 也显示值发生变化,但 while 没有结束(“完成”println 永远不会达到)。有趣的是,如果我们将打印放入 while... 然后就可以了!
I found a mysterious problem with a Java code for homework. A friend program an application which this at the beginning :
public void run() {
vm.setVisible(true);
while(!end);
System.out.println("Finish");
vm.setVisible(false);
}
The boolean 'end' is false while all the execution and when the user quits the application this happens:
private class CloseSys implements ActionListener {
public CloseSys() {super();}
public void actionPerformed(ActionEvent e) {
System.out.println("CLOSE SYS");
System.out.println("end: "+end);
end = true;
System.out.println("end: "+end);
}
}
The println shows like the value of 'end' changes to true and logically in my friend's computer (MacOS) the while finish and the application too.
The problem is that in my computer (Ubuntu Linux) the println also shows like the value changes but the while doesn't ends (the "Finish" println is never reached). The funny thing about it is if we put prints into the while... then works!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
其他几个人提到它应该是不稳定的。似乎还没有人提到的一件事是,你正在“忙着等待”,这是错误的,错误的,错误的错误。如果你想等待另一个线程中发生某些事情,你应该使用同步锁或 信号量。
Several other people have mentioned that it should be volatile. One thing nobody seems to have mentioned yet is that you are "busy waiting", which is wrong, wrong, wrongity wrong. If you want to wait for something to happen in another thread, you should use synchronization locks or Semaphores.
end
必须是易失性
,因为它在两个线程之间共享!end
must bevolatile
since its shared between two threads!尝试使
end
变量可变 - 您已被多线程问题困扰(并且您有一个多核 CPU)。以下是一些相关信息:http://www.javamex.com/tutorials/synchronization_volatile_when.shtml
Try to make the
end
variable volatile - you've been bitten by a multithreading issue (and you have a multi-core CPU).Here's some info on that: http://www.javamex.com/tutorials/synchronization_volatile_when.shtml
这看起来像是一个线程问题。
尝试将
end
声明为易失性
,或者最好仍然使用CountDownLatch
,因为这样可以避免占用 CPU:请注意
invokeAndWait
的使用code> 更改非 EDT 线程的窗口可见性。It looks like a threading issue.
Try declaring
end
asvolatile
, or better still use aCountDownLatch
as this avoids hogging a CPU:Note the use of
invokeAndWait
to change the window visibility from a non-EDT thread.