Java implementation of asynchronous call

一、创建线程
 @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 function performs end");

}

二、Future

  jdk8 before implementation, at JUC increased Future, is to understand the meaning of the future from the literal meaning, but must be really a bit tasteless, and can not achieve true asynchronous in the sense of, you need to block the thread getting results, or continuously polls .
@Test
public void test1 () throws Exception {

    System.out.println ( "main function started");

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

            System.out.println ( "Start Task === ===");
            the Thread.sleep (5000);
            System.out.println ( "Task Finish === ===");
            return. 3;
        }
    });
    will block the main thread is here // need to return value, if you do not use the return value is OK. The idea is also to receive
    // Integer Future.get the Result = ();
    System.out.println ( "main function performs end");

    System.in.read();

}

三、CompletableFuture

    Use native CompletableFuture asynchronous operations, plus support for lambda can be said asynchronous task has been to the extreme.
 @Test
public void test2 () throws Exception {
    System.out.println ( "main function started");
    ExecutorService = Executors.newFixedThreadPool Executor (2);
    CompletableFuture <Integer> = CompletableFuture.supplyAsync Future (new new Supplier <Integer> ( ) {
        @Override
        public GET Integer () {
            System.out.println ( "Start Task === ===");
            the try {
                the Thread.sleep (5000);
            } the catch (InterruptedException E) {
                e.printStackTrace ();
            }
            System.out.println ( "Task Finish === ===");
            return. 3;

    }, Executor);
    future.thenAccept (E -> System.out.println (E));
    System.out.println ( "main function execution finished");
}

Four, Spring of Async comment

xml manner:
<Task: Annotation-Driven Executor = "Executor" />
<Task: Executor ID = "Executor"
        the pool-size = "2" Thread pool size
        queue-capacity = "100" Queue Queue Length
        keep-alive = "120" thread keep alive time (in seconds)
        rejection-policy = "CALLER_RUNS" task processing policy rejected />

java方式:
@EnableAsync
public class MyConfig {

    @Bean
    public of TaskExecutor Executor () {
        the ThreadPoolTaskExecutor is the ThreadPoolTaskExecutor is Executor new new = ();
        executor.setCorePoolSize (10); // number of core threads
        executor.setMaxPoolSize (20); // Maximum number of threads
        executor.setQueueCapacity (1000); // queue size
        executor.setKeepAliveSeconds (300); // maximum thread idle time
        executor.setThreadNamePrefix ( "fsx-Executor-") ; // prefix specified thread name for the newly created.
        executor.setRejectedExecutionHandler (new new ThreadPoolExecutor.CallerRunsPolicy ());
        return Executor;
    }
}

(. 1) @Async
@Test
public void Test3 () throws Exception {
    System.out.println ( "main function started");
    myService.longtime ();
    System.out.println ( "main function execution finished");
}

 @Async
public void Longtime () {
    System.out.println ( "I perform a time-consuming tasks");
    the try {
        the Thread.sleep (5000);
    } the catch (InterruptedException E) {
        e.printStackTrace ();
    }
    the System .out.println ( "complete");

}

(2)AsyncResult

    If you need to return value, time-consuming method returns a value AsyncResult packaging.

@Test
public void Test4 () throws Exception {
    System.out.println ( "main function started");
    Future <Integer> = myService.longtime2 Future ();
    System.out.println ( "main function execution finished");
    System.out.println ( "asynchronous execution result:" + Future.get ());
}

 @Async
public Future <Integer> longtime2 () {
    System.out.println ( "I'm on a time-consuming task");

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

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

Guess you like

Origin www.linuxidc.com/Linux/2019-08/160253.htm