Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java实现异步的几种方法

作者:硝烟   发布日期:2026-04-20   浏览:82

// 方法1: 使用线程池和Future实现异步

import java.util.concurrent.*;

public class AsyncExample1 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        // 提交任务并获取Future对象
        Future<String> future = executor.submit(() -> {
            // 模拟耗时操作
            Thread.sleep(2000);
            return "Task completed";
        });

        // 可以做其他事情,然后在需要的时候获取结果
        System.out.println("Doing other tasks...");
        System.out.println("Result: " + future.get()); // 阻塞直到结果返回

        executor.shutdown();
    }
}

// 方法2: 使用CompletableFuture实现异步

import java.util.concurrent.CompletableFuture;

public class AsyncExample2 {
    public static void main(String[] args) throws Exception {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                // 模拟耗时操作
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Task completed";
        });

        // 可以做其他事情,然后在需要的时候获取结果
        System.out.println("Doing other tasks...");
        System.out.println("Result: " + future.get()); // 非阻塞方式等待结果

        // 也可以使用thenApply、thenAccept等方法链式调用
        CompletableFuture<Void> result = future.thenAccept(System.out::println);
        result.join(); // 等待所有操作完成
    }
}

// 方法3: 使用回调函数实现异步

public class AsyncExample3 {
    public static void main(String[] args) throws InterruptedException {
        MyAsyncTask task = new MyAsyncTask();
        task.executeAsync(result -> {
            System.out.println("Callback received result: " + result);
        });

        // 主线程可以继续执行其他任务
        System.out.println("Doing other tasks...");
        Thread.sleep(3000); // 模拟主线程继续工作
    }
}

class MyAsyncTask {
    public void executeAsync(MyCallback callback) {
        new Thread(() -> {
            try {
                // 模拟耗时操作
                Thread.sleep(2000);
                String result = "Task completed";
                callback.onComplete(result);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

interface MyCallback {
    void onComplete(String result);
}

解释说明:

  1. 使用线程池和Future实现异步

    • 创建一个线程池,并通过submit方法提交任务。
    • Future对象用于获取任务的结果。future.get()会阻塞当前线程,直到任务完成。
  2. 使用CompletableFuture实现异步

    • CompletableFuture是Java 8引入的类,提供了更灵活的异步编程模型。
    • supplyAsync方法用于异步执行任务,get方法同样会阻塞等待结果。
    • 还可以通过thenApplythenAccept等方法进行链式调用,实现非阻塞的操作。
  3. 使用回调函数实现异步

    • 定义一个接口MyCallback,并在任务完成后通过回调函数传递结果。
    • 主线程可以在任务执行期间继续处理其他任务,不会被阻塞。

这些方法都可以实现异步操作,具体选择哪种方法取决于你的需求和代码风格。

上一篇:java获取ip地址

下一篇:java+ai

大家都在看

java url decode

java判断是windows还是linux

java连接数据库的代码

java date类型比较大小

java djl

ubuntu 卸载java

es java api

java list 查找

java 解压rar

java读取excel中的图片

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站