在新线程中调用方法的简单方法

新手上路,请多包涵

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

我找到了像 ExecutorCallable 这样的类,但我不明白如何使用这些类。

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

感谢您的所有建议。

编辑: 该方法 必须 返回结果。此结果取决于参数。是这样的:

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

}

使用此代码我再次出错(即使我将 return null 放在 catch 块之外)。

原文由 Sk1X1 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 470
2 个回答

首先,我建议查看 Java Thread Documentation

使用线程,您可以传入一个名为 a Runnable 的接口类型。文档可以在 这里 找到。可运行对象是具有 run 方法的对象。当您启动一个线程时,它将调用此可运行对象的 run 方法中的任何代码。例如:

 Thread t = new Thread(new Runnable() {
         @Override
         public void run() {
              // Insert some method call here.
         }
});

现在,这意味着当您调用 t.start() 时,它将运行您需要的任何代码,而不会滞后于主线程。这称为 Asynchronous 方法调用,这意味着它与您打开的任何其他线程并行运行,例如 main 线程。 :)

原文由 christopher 发布,翻译遵循 CC BY-SA 3.0 许可协议

从 Java 8 开始,您可以使用更短的形式:

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

更新: 另外,您可以使用方法参考:

 class Example {

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

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

}

当您的参数列表与所需的 @FunctionalInterface 相同时,您可以使用它,例如 RunnableCallable

更新 2: 我强烈建议使用 java.util.concurrent.Executors#newSingleThreadExecutor() 来执行即发即弃任务。

例子:

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

查看更多: JavaFX 中的 Platform.runLaterTask方法参考

原文由 Andrii Abramov 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题