java asynchronous method call

A. Multithreading

Direct new threads

Thread t = new Thread(){
  @Override
  public void run() {
    longTimeMethod();
  }
};

Use the thread pool

private ExecutorService executor = Executors.newCachedThreadPool() ;

    public void fun() throws Exception {

        executor.submit(new Runnable(){

            @override

                public void run() {

                    try {
                     //要执行的业务代码,我们这里没有写方法,可以让线程休息几秒进行测试

                        Thread.sleep(10000);

                        System.out.print("睡够啦~");

                    }catch(Exception e) {

                        throw new RuntimeException("报错啦!!");

                    }

                }

        });

    }

II. Spring asynchronous method employed to execute (no return value)

In the startup class or class configuration plus @EnableAsync comment.

package me.deweixu.aysncdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync
@SpringBootApplication
public class AysncDemoApplication {

 public static void main(String[] args) {
  SpringApplication.run(AysncDemoApplication.class, args);
 }
}

Spring longTimeMethod first encapsulated into an asynchronous method, this method must be written in the management class Spring, attention annotation @Async

@Async Annotations can be used in the method can also be used in classes, with class, all methods for which the class act

@Service
public class AsynchronousService{
  @Async
  public void springAsynchronousMethod(){
    longTimeMethod();
  }
}

Other classes call this method. Here attention must be other classes, if you call in its kind, is not in force. Specific reasons, can go to learn about the principles of Spring AOP

@Autowired
private AsynchronousService asynchronousService;

public void useAsynchronousMethod(){
  //我们需要执行的代码1
  asynchronousService.springAsynchronousMethod();
 //我们需要执行的代码2
}

III. Spring asynchronous method using the return value within + Future

Spring longTimeMethod first package to asynchronous method, this method's return value is asynchronous Future examples. This approach must be written in Spring management class, pay attention to notes @Async.

@Service
public class AsynchronousService{
  @Async
  public Future springAsynchronousMethod(){
    Integer result = longTimeMethod();
    return new AsyncResult(result);
  }
}

Other classes call this method. Here attention must be other classes, if you call in its kind, is not in force.

If you call after receiving the return value, the return value of the operation was not an asynchronous operation, the operation would be transformed into synchronous operation, wait for the process to return value after completion of operation, we will continue to implement the following main process

@Autowired
private AsynchronousService asynchronousService;

public void useAsynchronousMethod(){
    Future future = asynchronousService.springAsynchronousMethod();
    future.get(1000, TimeUnit.MILLISECONDS);
}

IV. Future Native Method

//我们需要执行的代码1
Future future = longTimeMethod2();
//我们需要执行的代码2
Integer result = future.get();

You can see, we call longTimeMethod2 returns a Future object (attention, longTimeMethod2 here is certainly not above longTimeMethod), and then deal with "the code we need to do 2", to the need to return results when called directly future.get () will able to get a return value. Let us look at how longTimeMethod2 achieve.

private Future longTimeMethod2() {
  //创建线程池
  ExecutorService threadPool = Executors.newCachedThreadPool();
  //获取异步Future对象
  Future future = threadPool.submit(new Callable() {
    @Override
    public Integer call() throwsException {
        return longTimeMethod();
    }
  });
  return future;
}

reference

Original link: https: //www.jianshu.com/p/51f0555b232a

Guess you like

Origin www.cnblogs.com/eternityz/p/12238830.html