有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程如何在java线程内调用异步方法?

在Java中,有没有办法在线程内调用和处理异步方法

考虑一个场景,其中线程主体中的一个方法需要更多的时间来执行它。因此,线程完成需要更多的时间

我尝试了一些使用并发包类的例子,比如FutureTask和Executors

是否可以在异步方法中实现和处理所有异常?在JavaScript中是否可能获得成功或错误响应,如AJAX成功和错误处理程序

我们将如何确保异步方法成功执行或不执行(有或没有父线程上下文)


共 (1) 个答案

  1. # 1 楼答案

    异步方法和父线程之间最自然的通信方式是标准类CompletableFuture

    import java.util.concurrent.CompletableFuture;
    import java.util.concurrent.ExecutionException;
    
    public class AsyncExample { 
        String input; // common data
    
        // async method
        public String toLower() {
            return input.toLowerCase();
        }
    
        // method on main thread
        public void run() {
            input = "INPUT"; // set common data
            try {
                // start  async method
                CompletableFuture<String> future = CompletableFuture.supplyAsync(this::toLower);
                // here we can work in parallel
                String result = future.get(); // get the async result
                System.out.println("input="+input+"; result="+result);
            } catch (InterruptedException | ExecutionException e) {
            }
        }
    
        public static void main(String[] args) {
            new AsyncExample().run();
        }
    }
    

    请注意Executor的创建和预热(包括示例中使用的默认执行器)需要一些时间(在我的计算机上为50毫秒),因此您可能希望事先创建并预热一个,例如通过提供空方法:

          CompletableFuture.supplyAsync(()->null).get();