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

Sk1*_*1X1 13 java multithreading javafx ui-thread

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

我发现类,如ExecutorCallable,但我不知道如何与那些工作.

你可以发布任何解决方案,这对我有帮助吗?

谢谢你的所有建议.

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

public static HtmlPage getPage(String page) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
        return webClient.getPage(page);
}
Run Code Online (Sandbox Code Playgroud)

此方法大约需要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;
    }

}
Run Code Online (Sandbox Code Playgroud)

使用此代码,我再次收到错误(即使我return null放出了catch块).

And*_*mov 31

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

new Thread(() -> {
    // Insert some method call here.
}).start();
Run Code Online (Sandbox Code Playgroud)

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

class Example {

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

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

}
Run Code Online (Sandbox Code Playgroud)

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

例:

Executors
    .newSingleThreadExecutor()
    .submit(Example::someMethod);
Run Code Online (Sandbox Code Playgroud)

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

查看更多: Platform.runLaterTaskJavaFX中,方法引用.


chr*_*her 27

首先,我建议查看Java Thread Documentation.

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

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

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


Rah*_*ngh 6

在Java 8中,如果不需要参数,您可以使用:

new Thread(MyClass::doWork).start();
Run Code Online (Sandbox Code Playgroud)

或者在参数的情况下:

new Thread(() -> doWork(someParam))
Run Code Online (Sandbox Code Playgroud)