服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - java异步调用的4种实现方法

java异步调用的4种实现方法

2022-09-12 14:48未月廿三 Java教程

日常开发中,会经常遇到说,前台调服务,本文主要介绍了java异步调用的4种实现方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

一.利用多线程

直接new线程

?
1
2
3
4
5
6
Thread t = new Thread(){
  @Override
  public void run() {
    longTimeMethod();
  }
};

使用线程池

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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("报错啦!!");
 
                    }
 
                }
 
        });
 
    }

二.采用Spring 的异步方法去执行(无返回值)

在启动类或者配置类加上 @EnableAsync 注解.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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);
 }
}

先把longTimeMethod 封装到Spring的异步方法中,这个方法一定要写在Spring管理的类中,注意注解@Async

@Async注解可以用在方法上,也可以用在类上,用在类上,对类里面所有方法起作用

?
1
2
3
4
5
6
7
@Service
public class AsynchronousService{
  @Async
  public void springAsynchronousMethod(){
    longTimeMethod();
  }
}

其他类调用这个方法。这里注意,一定要其他的类,如果在同类中调用,是不生效的。具体原因,可以去学习一下Spring AOP的原理

?
1
2
3
4
5
6
7
8
@Autowired
private AsynchronousService asynchronousService;
 
public void useAsynchronousMethod(){
  //我们需要执行的代码1
  asynchronousService.springAsynchronousMethod();
 //我们需要执行的代码2
}

三.采用Spring 的异步方法+Future接收返回值

先把longTimeMethod 封装到Spring的异步方法中,这个异步方法的返回值是Future的实例。这个方法一定要写在Spring管理的类中,注意注解@Async。

?
1
2
3
4
5
6
7
8
@Service
public class AsynchronousService{
  @Async
  public Future springAsynchronousMethod(){
    Integer result = longTimeMethod();
    return new AsyncResult(result);
  }
}

其他类调用这个方法。这里注意,一定要其他的类,如果在同类中调用,是不生效的。

如果调用之后接收返回值,不对返回值进行操作则为异步操作,进行操作则转为同步操作,等待对返回值操作完之后,才会继续执行主进程下面的流程

?
1
2
3
4
5
6
7
@Autowired
private AsynchronousService asynchronousService;
 
public void useAsynchronousMethod(){
    Future future = asynchronousService.springAsynchronousMethod();
    future.get(1000, TimeUnit.MILLISECONDS);
}

四.原生Future方法

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

可以看到,我们调用longTimeMethod2返回一个Future对象(注意了,这里的longTimeMethod2当然不是上面的longTimeMethod),然后处理“我们需要执行的代码2”,到了需要返回结果的时候直接调用future.get()便能获取到返回值。下面我们来看看longTimeMethod2如何实现。

?
1
2
3
4
5
6
7
8
9
10
11
12
private Future longTimeMethod2() {
  //创建线程池
  ExecutorService threadPool = Executors.newCachedThreadPool();
  //获取异步Future对象
  Future future = threadPool.submit(new Callable() {
    @Override
    public Integer call() throwsException {
        return longTimeMethod();
    }
  });
  return future;
}

参考

原文链接:https://www.jianshu.com/p/51f0555b232a

到此这篇关于java异步调用的4种实现方法的文章就介绍到这了,更多相关java异步调用内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/eternityz/p/12238830.html

延伸 · 阅读

精彩推荐