16

我正在编写小应用程序,现在我发现了一个问题。我需要调用一个(稍后可能是两个)方法(此方法加载一些内容并返回结果)而不滞后于应用程序窗口。

Executor我找到了or之类的类Callable,但我不明白如何使用这些类。

您能否发布任何对我有帮助的解决方案?

感谢所有建议。

编辑:该方法必须返回结果。这个结果取决于参数。像这样的东西:

public static HtmlPage getPage(String page) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
        return webClient.getPage(page);
}

此方法大约工作 8-10 秒。执行此方法后,可以停止线程。但我需要每 2 分钟调用一次方法。

编辑:我用这个编辑了代码:

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;
    }

}

With this code I get error again (even if I put return null out of catch block).

4

3 回答 3

36

Since Java 8 you can use shorter form:

new Thread(() -> {
    // Insert some method call here.
}).start();

Update: Also, you could use method reference:

class Example {

    public static void main(String[] args){
        new Thread(Example::someMethod).start();
    }

    public static void someMethod(){
        // Insert some code here
    }

}

You are able to use it when your argument list is the same as in required @FunctionalInterface, e.g. Runnable or Callable.

Update 2: I strongly recommend utilizing java.util.concurrent.Executors#newSingleThreadExecutor() for executing fire-and-forget tasks.

Example:

Executors
    .newSingleThreadExecutor()
    .submit(Example::someMethod);

See more: Platform.runLater and Task in JavaFX, Method References.

于 2015-10-27T19:22:06.873 回答
28

Firstly, I would recommend looking at the Java Thread Documentation.

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.
         }
});

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. :)

于 2013-04-07T19:59:46.470 回答
7

In Java 8 if there is no parameters required you can use:

new Thread(MyClass::doWork).start();

Or in case of parameters:

new Thread(() -> doWork(someParam))
于 2016-11-01T13:39:00.760 回答