文章字数:263,阅读全文大约需要1分钟
java程序与第三方系统交互的时候使用同步容易造成响应迟缓,解决方法除了多线程之外还可以使用Spring内置的@Async
来解决这个问题
开启注解
1 2 3 4 5 6 7 8 9
| @ComponentScan(basePackages = { "com.xwj.controller", "com.xwj.service" }) @EnableAsync @EnableAutoConfiguration public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
|
无返回值调用
1 2 3 4
| @Async public void asyncMethodWithVoidReturnType() { System.out.println("获取:"+ Thread.currentThread().getName()); }
|
有返回值
异步方法
1 2 3 4 5 6 7 8 9
| @Async public Future<String> asyncMethodWithReturnType() { try{ Thread.sleep(5000); return new AsynResult<String>("hello"); } return null; }
|
调用
1 2 3 4 5 6 7
| public void test() throws InterruptedException, ExecutionException{ Future<String> future = asyncMethodWithReturnType(); future.get(); future.cancel(boolean mayInterruptIfRunning); future.isDone(); future.isCancel(); }
|
Future接口
1 2 3 4 5 6 7 8 9 10 11 12
| public static void main(String[] args)throws InterruptedException,ExecutionException{ Callable ca1 = new Callable(){ @Override public String call() throws Exception{ return "xxx"; } FutureTask<String> ft1 = new FutureTask<String>(ca1); new Thread(ft1).start(); System.out.println(ft1.get()); } }
|