问题描述
我正在编写小应用程序,现在我发现了一个问题。
我需要调用一个(稍后可能是两个)方法(这个方法加载一些东西并返回结果)而不会滞后于app的窗口。
I'm writing small app and now I discovered a problem.I need to call one(later maybe two) method (this method loads something and returns the result) without lagging in window of app.
我找到了类喜欢执行者
或可调用
,但我不明白如何使用这些。
I found classes like Executor
or Callable
, but I don't understand how to work with those ones.
您能否发布任何解决方案,这对我有帮助吗?
Can you please post any solution, which helps me?
感谢所有建议。
编辑方法必须返回结果。此结果取决于参数。
这样的事情:
The method MUST return the result. This result depends on parametrs.Something like this:
public static HtmlPage getPage(String page) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
return webClient.getPage(page);
}
此方法大约需要8-10秒。执行此方法后,可以停止线程。但我需要每2分钟调用一次方法。
This method works about 8-10 seconds. After execute this method, thread can be stopped. But I need to call the methods every 2 minutes.
编辑:我用以下代码编辑了代码:
I edited code with this:
public static HtmlPage getPage(final String page) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
Thread thread = new Thread() {
public void run() {
try {
loadedPage = webClient.getPage(page);
} catch (FailingHttpStatusCodeException | IOException e) {
e.printStackTrace();
}
}
};
thread.start();
try {
return loadedPage;
} catch (Exception e) {
return null;
}
}
使用此代码我再次收到错误(即使我把从 catch 块中返回null
)。
With this code I get error again (even if I put return null
out of catch block).
推荐答案
首先,我建议您查看。
Firstly, I would recommend looking at the Java Thread Documentation.
使用Thread,您可以传入一个名为 Runnable
的接口类型。可以在找到该文档。 runnable是一个具有 run
方法的对象。当你启动一个线程时,它将调用这个runnable对象的 run
方法中的任何代码。例如:
With a Thread, you can pass in an interface type called a Runnable
. The documentation can be found here. A runnable is an object that has a run
method. When you start a thread, it will call whatever code is in the run
method of this runnable object. For example:
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// Insert some method call here.
}
});
现在,这意味着当你致电 t.start()时/ code>,它将运行您需要的任何代码而不会滞后主线程。这称为
异步
方法调用,这意味着它与您打开的任何其他线程并行运行,例如 main
线程。 :)
Now, what this means is when you call t.start()
, it will run whatever code you need it to without lagging the main thread. This is called an Asynchronous
method call, which means that it runs in parallel to any other thread you have open, like your main
thread. :)
这篇关于在新线程中调用方法的简便方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!