Skip to content

异步执行

更新: 2/21/2025 字数: 0 字 时长: 0 分钟

在Java开发中异步执行是常用的技术手段,它可以提高程序的执行效率,特别是在处理耗时操作(如网络请求、文件读写等)时。 Java提供了多种方式来实现异步执行,包括使用Future,CompletableFuture,以及Java 8引入的CompletableFuture等。

异步执行方式

使用 Thread 类

java

@Slf4j
@DisplayName("异步执行")
class AsyncTest {

  @Test
  @DisplayName("示例Thread类")
  void threadTest() {
    Thread thread = new Thread(() -> {
      // 模拟耗时操作
      try {
        Thread.sleep(2000);
      } catch (InterruptedException ignored) {
      }
      log.info("耗时操作完成");
    });
    thread.start();
    log.info("主线程执行完毕");
  }

}

使用Runnable接口

java
@Slf4j
@DisplayName("异步执行")
class AsyncTest {
  
  @Test
  @DisplayName("示例Runnable接口")
  void runnableTest() {
    Runnable task = () -> {
      try {
        // 模拟耗时操作
        Thread.sleep(2000);
      } catch (InterruptedException ignored) {
      }
      log.info("耗时操作完成");
    };
    new Thread(task).start();
    log.info("主线程执行完毕");
  }

}

使用Future

java
@Slf4j
@DisplayName("异步执行")
class AsyncTest {
  
  @Test
  @DisplayName("示例Future")
  void futureTest() {
    ExecutorService executor = Executors.newFixedThreadPool(1);
    try {
      Future<String> future = executor.submit(() -> {
        // 模拟耗时操作
        try {
          Thread.sleep(2000);
        } catch (InterruptedException ignored) {
        }
        log.info("耗时操作完成");
        return "恭喜完成任务!";
      });
      String result = future.get(); // 阻塞,直到任务执行完毕
      log.info("异步执行结果: {}", result);
    } finally {
      executor.shutdown();
    }
    log.info("主线程执行完毕");
  }

}

使用CompletableFuture

java
@Slf4j
@DisplayName("异步执行")
class AsyncTest {

  @Test
  @DisplayName("示例CompletableFuture")
  void completableFutureTest() {
    CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
      try {
      // 模拟耗时操作
        Thread.sleep(2000);
      } catch (InterruptedException ignored) {
      }
      log.info("耗时操作完成");
    });
    future.thenRun(() -> log.info("异步执行完毕"));
    log.info("主线程执行完毕");
  }

}