代码在正常运行时不工作,但在调试(eclipse)中工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17070627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Code not working when running normally, but working in debug (eclipse)
提问by Creator13
I'm really confused by this: some of my code is not working when i run my program normally in eclipse, but it does wok when i run through each step separately using the debug mode.
我真的对此感到困惑:当我在 eclipse 中正常运行我的程序时,我的某些代码无法正常工作,但是当我使用调试模式分别运行每个步骤时,它确实起作用了。
Code:
代码:
public void showConnectDialog() {
ConnectDialog connectDialog = new ConnectDialog();
connectDialog.setVisible(true);
//Until here, code runs
while(! connectDialog.getConnected()) {};
//The next line does only run in debug
JOptionPane.showMessageDialog(connectDialog, "Connected", "Connected", JOptionPane.INFORMATION_MESSAGE);
}
The connector (is started (as a thread) as soon as the user hits 'connect' in the dialog):
连接器(在用户点击对话框中的“连接”后立即启动(作为线程)):
private class ServerConnector implements ActionListener, Runnable {
@Override
public void actionPerformed(ActionEvent e) {
if (! IP_field.getText().equals("")) {
if (! isConnecting) {
new Thread(new ServerConnector(), "ServerConnector").start();
}
}
else {
JOptionPane.showMessageDialog(dialog,
"Enter an IP address",
"Enter IP",
JOptionPane.WARNING_MESSAGE);
}
}
@Override
public void run() {
try {
setConnecting(true);
Socket socket = connect();
if (socket != null) {
ObjectOutputStream oOut = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream oIn = new ObjectInputStream(socket.getInputStream());
if (login(oOut, oIn)) {
isConnected = true;
setConnecting(false);
}
else {
socket.close();
}
setConnecting(false);
}
}
catch (RSPException e) {
e.printStackTrace();
System.exit(1);
}
catch (Exception e) {
//If an exception occurs, setConnecting() will be true. This
//not good, so it has to be set to false
e.printStackTrace();
setConnecting(false);
}
}
private boolean login(ObjectOutputStream oOut, ObjectInputStream oIn)
throws ClassNotFoundException, IOException, RSPException {
//Send login request action:
oOut.writeObject(new LoginAction(ActionSender.CLIENT, getID(),
getPassword()));
Object obj = oIn.readObject();
if (obj instanceof LoginActionResult) {
LoginActionResult result = (LoginActionResult) obj;
if (result.getResult() == LoginResults.SUCCES) {
return true;
}
else if (result.getResult() == LoginResults.FAIL_ON_ID) {
JOptionPane.showMessageDialog(dialog,
"Invalid password or ID",
"Can't login",
JOptionPane.ERROR_MESSAGE);
return false;
}
else if (result.getResult() == LoginResults.FAIL_ON_PASSWORD) {
JOptionPane.showMessageDialog(dialog,
"Invalid password or ID",
"Can't login",
JOptionPane.ERROR_MESSAGE);
return false;
}
else if (result.getResult() == LoginResults.SERVER_FULL) {
JOptionPane.showMessageDialog(dialog,
"Couldn't connect: \n" +
"Server is full",
"Failed to connect",
JOptionPane.WARNING_MESSAGE);
return false;
}
else {
return false;
}
}
else {
System.out.println(obj);
throw new RSPException("Server is not following the protocol.");
}
}
private void setConnecting(boolean connecting) {
if (connecting) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
connectButton.setEnabled(false);
}
});
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
connectButton.setText("Connecting...");
}
});
}
else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
connectButton.setText("Connect");
}
});
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
connectButton.setEnabled(true);
}
});
}
isConnecting = connecting;
}
private String getAddressFromTextField() {
return IP_field.getText();
}
private InetAddress getInetAddress(String fullAddress) {
try {
if (fullAddress.contains(":")) {
String[] splitAddress = fullAddress.split(":");
return InetAddress.getByName(splitAddress[0]);
}
else {
return InetAddress.getByName(fullAddress);
}
}
catch (UnknownHostException e) {
return null;
}
}
private int getPort(String fullAddress) {
try {
String[] splittedAddress = fullAddress.split(":");
return Integer.valueOf(splittedAddress[1]);
}
catch (NumberFormatException ex) {
return -1;
}
catch (NullPointerException
| ArrayIndexOutOfBoundsException
| PatternSyntaxException ex) {
//Returning default port value: 25566, because no port was given
return 25566;
}
}
@SuppressWarnings("resource")
private Socket connect() {
Socket socket = null;
InetAddress address = null;
if ((address = getInetAddress(getAddressFromTextField())) == null) {
return null;
}
int port = getPort(getAddressFromTextField());
try {
socket = new Socket(address, port);
}
catch (ConnectException e ) {
Socket retrySocket = null;
if ((retrySocket = retryConnect(address, port)) == null) {
JOptionPane.showMessageDialog(dialog,
"Connection timed out",
"Failed to connect",
JOptionPane.ERROR_MESSAGE);
setConnecting(false);
}
else {
socket = retrySocket;
}
}
catch(IOException e) {
e.printStackTrace();
}
return socket;
}
private Socket retryConnect(InetAddress address, int port) {
Thread waitThread = new Thread(new Runnable() {
@Override
public void run() {
try {
//Will wait 15(000) (milli)seconds before stopping with
//trying to connect.
//One second (1000 millis) is for debugging and testing
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
waitThread.start();
while (waitThread.isAlive()) {
try {
return new Socket(address, port);
}
catch (ConnectException e) {
//Do nothing, will re-attempt to connect.
}
catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
private String getID() {
return ID_field.getText();
}
private String getPassword() {
if (getID().equals("master")) {
return "masterPassword";
}
else {
return new String(passwordField.getPassword());
}
}
}
getConnected()
returns true
as soon as it's connected to the server. The connector is running on a separate thread.
getConnected()
true
连接到服务器后立即返回。连接器在单独的线程上运行。
EDIT: I tried to put code in the getConnected()
while block, and then it works. Why does it works then and not else?
编辑:我试图将代码放在getConnected()
while 块中,然后它就可以工作了。为什么它当时有效而不是其他?
回答by DomLavoie
I had the same Problem, but with some more specification. The code was working fine in 32bit but I had this issue in 64bit (I am using native library so I need to maintain both).
我有同样的问题,但有更多的规范。代码在 32 位上运行良好,但我在 64 位中遇到了这个问题(我使用的是本机库,所以我需要同时维护两者)。
The solution I found is to add Thread.sleep() in the while loop. I don't know why it works, so your guess is as good as mine.
我找到的解决方案是在 while 循环中添加 Thread.sleep() 。我不知道它为什么有效,所以你的猜测和我的一样好。
A better solution would probably to implement an Observer Patterninstead of having an infinite loop. But that would require some re-factoring.
更好的解决方案可能是实现观察者模式而不是无限循环。但这需要一些重构。
回答by tudor balus
I had a very similar problem with a "while" loop that wouldn't run and that loop was my main routine. How I got the loop to run was that the very first thing that was done in the loop was a sleep:
我有一个与“while”循环非常相似的问题,该循环无法运行,而该循环是我的主要例程。我如何让循环运行是循环中完成的第一件事是睡眠:
try
{Thread.sleep(0);}
catch (Exception e)
{e.printStackTrace();}
This was enough to get everything going.
这足以让一切顺利。
回答by vish4071
Using Thread.sleep()
, as the other answers have suggested, should solve the problem but it is not a very good approach. Instead, we should be using Thread.yield()
.
使用Thread.sleep()
,因为其他的答案都建议,要解决这个问题,但它不是一个很好的办法。相反,我们应该使用Thread.yield()
.
Why yield
and not sleep
?
为什么yield
不sleep
?
Refer: Difference between Thread.Sleep(0) and Thread.Yield()and Are Thread.sleep(0) and Thread.yield() statements equivalent?
请参阅: Thread.Sleep(0) 和 Thread.Yield() 之间的区别以及Thread.sleep(0) 和 Thread.yield() 语句是否等效?
Why this works?
为什么这有效?
When we just run the threads, the OS puts them to "idle" state and when it is expected to "wake-up", it does not. On the other hand, in debug mode, we have a controlled environment. The OS has little control over it as everything goes on step-by-step, slowly. If we run the debug a few times without any break-points, after a few successful runs, we should see the same effect.
当我们只运行线程时,操作系统将它们置于“空闲”状态,而当预计“唤醒”时,它不会。另一方面,在调试模式下,我们有一个受控环境。操作系统几乎无法控制它,因为一切都在一步一步、缓慢地进行。如果我们在没有任何断点的情况下运行调试几次,在几次成功运行后,我们应该看到相同的效果。
回答by Wladek Ignatenko
I had same problem in UIAutomator with UiObject2 wait(Until.findObject(),20) .
我在 UIAutomator 和 UiObject2 wait(Until.findObject(),20) 中遇到了同样的问题。
Thread.yield() - works for me
Thread.yield() - 对我有用