教你如何用 Java 實現異步調用

導讀 本教程教你如何使用Java實現異步調用。

1、建立線程html

@Test
public void test0() throws Exception {
  System.out.println("main函數開始執行");
  Thread thread=new Thread(new Runnable() {
    @Override
    public void run() {
      System.out.println("===task start===");
      try {
        Thread.sleep(5000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println("===task finish===");
    }
  });

  thread.start();
  System.out.println("main函數執行結束");

}

2、Futurejava

jdk8以前的實現方式,在JUC下增長了Future,從字面意思理解就是將來的意思,但使用起來卻着實有點雞肋,並不能實現真正意義上的異步,獲取結果時須要阻塞線程,或者不斷輪詢。linux

@Test
public void test1() throws Exception {

    System.out.println("main函數開始執行");

    ExecutorService executor = Executors.newFixedThreadPool(1);
    Future<Integer> future = executor.submit(new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {

            System.out.println("===task start===");
            Thread.sleep(5000);
            System.out.println("===task finish===");
            return 3;
        }
    });
    //這裏須要返回值時會阻塞主線程,若是不須要返回值使用是OK的。倒也還能接收
    //Integer result=future.get();
    System.out.println("main函數執行結束");

    System.in.read();

}

3、CompletableFuturespring

使用原生的CompletableFuture實現異步操做,加上對lambda的支持,能夠說實現異步任務已經發揮到了極致。異步

@Test
public void test2() throws Exception {
    System.out.println("main函數開始執行");
    ExecutorService executor = Executors.newFixedThreadPool(2);
    CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {
        @Override
        public Integer get() {
            System.out.println("===task start===");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("===task finish===");
            return 3;
        }
    }, executor);
    future.thenAccept(e -> System.out.println(e));
    System.out.println("main函數執行結束");
}

4、Spring的Async註解async

使用spring實現異步須要開啓註解,能夠使用xml方式或者Java config的方式。ide

xml方式:函數

<task:annotation-driven executor="executor" />
<task:executor id="executor"
        pool-size="2" 線程池的大小
        queue-capacity="100" 排隊隊列長度 
        keep-alive="120" 線程保活時間(單位秒)
        rejection-policy="CALLER_RUNS" 對拒絕的任務處理策略 />

java方式:.net

@EnableAsync
public class MyConfig {

    @Bean
    public TaskExecutor executor(){
        ThreadPoolTaskExecutor executor=new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10); //核心線程數
        executor.setMaxPoolSize(20);  //最大線程數
        executor.setQueueCapacity(1000); //隊列大小
        executor.setKeepAliveSeconds(300); //線程最大空閒時間
        executor.setThreadNamePrefix("fsx-Executor-"); //指定用於新建立的線程名稱的前綴。
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}

(1)@Async線程

@Test
public void test3() throws Exception {
    System.out.println("main函數開始執行");
    myService.longtime();
    System.out.println("main函數執行結束");
}

 @Async
public void longtime() {
    System.out.println("我在執行一項耗時任務");
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("完成");

}

(2)AsyncResult

若是須要返回值,耗時方法返回值用AsyncResult包裝。

@Test
public void test4() throws Exception {
    System.out.println("main函數開始執行");
    Future future=myService.longtime2();
    System.out.println("main函數執行結束");
    System.out.println("異步執行結果:"+future.get());
}

 @Async
public Future longtime2() {
    System.out.println("我在執行一項耗時任務");

    try {
        Thread.sleep(8000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println("完成");
    return new AsyncResult<>(3);
}

原文來自: https://www.linuxprobe.com/java-async.html

相關文章
相關標籤/搜索