如何将一段代码延迟到回电之后



在方法中,我需要调用一些代码,但在方法的返回调用之后。 我该怎么做?

// this call needs to happen after the return true call  
xmlRpcClient.invoke("newDevices", listDeviceDesc);
return true;

就像约翰霍普金斯所说的那样,在调用返回后使用try{return true;}finally{yourCode}执行代码。但恕我直言,这没有经过适当的考虑,我会改变程序的设计。你能告诉我们更多关于你背后的想法,以了解你的方式吗?

您可能想做什么:

public void myMethod() {
  return true;
}
if(myMethod()) {
  client.invoke()
}

您可以使用匿名线程来实现您想要的内容,并在内部添加一秒钟的延迟。

try{return true;}finally{yourCode}不会这样做,因为 finally 将在方法实际返回之前执行。

new Thread() {
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // this call needs to happen after the return true call  
        xmlRpcClient.invoke("newDevices", listDeviceDesc);
    }
}.start();
return true;

我正在阅读Java中的finally块,我了解到它将始终被执行,除非JVM崩溃或调用System.exit()。更多信息可以在这个StackOverflow问题中找到。鉴于此信息,这应该对您有用。

try {
    return true;
} catch (Exception e) {
    // do something here to deal with anything
    // that somehow goes wrong just returning true
} finally {
    xmlRpcClient.invoke("newDevices", listDeviceDesc);
}

IMO,在调用方法处理返回值之前执行某些操作与在返回之前执行某些操作是没有区别的,因此您应该问问自己,您希望它何时发生。

在 Swing GUI 应用程序中,您可以使用 SwingUtilities.invokeLater 来延迟可运行的执行,直到"其他所有操作"完成。当单个用户操作导致执行大量侦听器时,这有时很有用(一个组件失去焦点,另一个组件获得焦点,并且所述其他组件也被激活......只需单击鼠标即可完成所有操作)。

最新更新