java实现异步的几种方法

Z, ZLW 985

java实现异步的4种方法:1、开线程;2、Future;3、CompletableFuture;4、Async注解

1、开线程

  • 开线程
    */
    public class ThreadTest { public void test() {
    new Thread(() -> {
    //做处理
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }).start();
    }
    }

2、Future

/**

  • Future
    */
    public class FutureTest {
    public void test() throws ExecutionException, InterruptedException {
    ExecutorService executorService = Executors.newFixedThreadPool(1);
    Future submit = executorService.submit(new Callable() {
    @Override
    public String call() throws Exception {
    //做处理
    Thread.sleep(1000);
    return “hello”;
    }
    }); //如果需要返回值的话,会阻塞主线程。 String s = submit.get(); }
    }

3、CompletableFuture

/**

  • CompletableFuture
    */
    public class CompletableFutureTest {
    public void test() {
    ExecutorService executorService = Executors.newFixedThreadPool(1);
    CompletableFuture c = CompletableFuture.supplyAsync(new Supplier() {
    @Override
    public String get() {
    //做处理
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return “hello”;
    }
    }, executorService); c.thenAccept(item -> System.out.println(item)); }
    }

4、Async

/**

  • Async注解:要在Spring中使用。
  • 1、首先在启动类上开启注解@EnableAsync
  • 2、然后需要异步操作的方法上加上@Async
    */
    public class AsyncTest {
    @Async
    public void test() throws InterruptedException {
    //做处理
    Thread.sleep(1000);
    } /**
    • 如果需要返回值的话,通过AsyncResult进行封装
      */
      @Async
      public Future testReturn() throws InterruptedException {
      //做处理
      Thread.sleep(1000);
      return new AsyncResult<>(“hello”);
      }
      }

回复

我来回复
  • 暂无回复内容

站长微信
站长微信
电话联系

400-800-1024

工作日9:30-21:00在线

分享本页
返回顶部