1.我们先介绍java8 的异步调用:CompletableFuture
用CompletableFuture.supplyAsync()定义要执行的异步任务
public class java8Async {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
// CompletableFuture.supplyAsync(),定义要执行的异步任务
CompletableFuture.supplyAsync(new Supplier() {
@Override
public String get() {
// TODO Auto-generated method stub
try {
System.out.println("任务1");
// 睡眠1s
TimeUnit.SECONDS.sleep(1);
System.out.println("任务2");
} catch (Exception e) {
e.printStackTrace();
}
return "返回数据async";
}
}, executor);
// return
System.out.println("任务执行完成");
}
}
执行结果:
当异步任务需要返回数据那怎么办呢?
用cupdResult.thenAccept(new Consumer
public class java8Async {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
// CompletableFuture.supplyAsync(),定义要执行的异步任务
CompletableFuture asyncResult = CompletableFuture.supplyAsync(new Supplier() {
@Override
public String get() {
// TODO Auto-generated method stub
try {
System.out.println("任务1");
// 睡眠1s
TimeUnit.SECONDS.sleep(1);
System.out.println("任务2");
} catch (Exception e) {
e.printStackTrace();
}
return "返回数据async";
}
}, executor);
// asyncResult.thenAccept(new Consumer() , 重写accept()方法去定义回调函数
asyncResult.thenAccept(new Consumer() {
public void accept(String arg0) {
System.out.println("return =" + arg0);
}
});
// return
System.out.println("任务执行完成");
}
}
执行结果:
2.我们介绍springboot的异步任务:springboot给我们提供了注解方法,在启动类上添加@EnableAsync注解,在需要用到异步任务的实现方法上添加@Async注解,然后就可以用了,详情如下:
启动类:添加@EnableAsync注解
package com.async;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @ClassName: OtherApplication
* @Description: TODO()
* @author lixin([email protected])
* @date 2018年10月13日 下午4:43:35
* @version V1.0
*/
@SpringBootApplication
@EnableTransactionManagement
@EnableAsync
public class OtherApplication {
public static void main(String[] args) {
SpringApplication.run(OtherApplication.class, args);
}
}
然后在你需要异步调用的方法上添加注解
package com.async.boot;
import java.util.concurrent.Future;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @ClassName: AsyncAfterServiceImpl
* @Description: TODO()
* @author lixin([email protected])
* @date 2018年10月13日 下午4:50:38
* @version V1.0
*/
@Service
public class AsyncAfterServiceImpl implements AsyncAfterService{
@Transactional
@Override
@Async
public Future asyncAfterOne() throws InterruptedException {
System.err.println("asyncAfterOne任务以执行");
return new AsyncResult("asyncAfterOne执行完毕");
}
@Transactional
@Override
@Async
public Future asyncAfterTwo() throws InterruptedException {
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(3000);
long currentTimeMillis1 = System.currentTimeMillis();
System.err.println("asyncAfterTwo任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
return new AsyncResult("asyncAfterTwo执行完毕");
}
@Transactional
@Override
@Async
public Future asyncAfterThree() throws InterruptedException {
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(6000);
long currentTimeMillis1 = System.currentTimeMillis();
System.err.println("asyncAfterThree任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
return new AsyncResult("asyncAfterThree执行完毕");
}
}
然后是调用类:
package com.async.boot;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @ClassName: AsyncServiceImpl
* @Description: TODO()
* @author lixin([email protected])
* @date 2018年10月13日 下午4:54:15
* @version V1.0
*/
@Service
public class AsyncServiceImpl implements AsyncService{
@Autowired
private AsyncAfterService asyncAfterService;
@Transactional
@Override
public String asyncOne() throws InterruptedException {
long currentTimeMillis = System.currentTimeMillis();
asyncAfterService.asyncAfterOne();
asyncAfterService.asyncAfterTwo();
asyncAfterService.asyncAfterThree();
long currentTimeMillis1 = System.currentTimeMillis();
return "asyncAfter任务总耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms";
}
@Transactional
@Override
public String asyncTwo() throws InterruptedException, ExecutionException {
long currentTimeMillis = System.currentTimeMillis();
Future two = asyncAfterService.asyncAfterTwo();
Future three = asyncAfterService.asyncAfterThree();
String result = null;
while (true) {
if(two.isDone() && three.isDone()) {
System.err.println(two.get());
System.err.println(three.get());
// 两个任务都调用完成,跳出循环
break;
}
Thread.sleep(1000);
}
long currentTimeMillis1 = System.currentTimeMillis();
result = "asyncAfter任务总耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms";
return result;
}
}
然后是测试类:
package com.async;
import java.util.concurrent.ExecutionException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.async.boot.AsyncService;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = OtherApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EnableAutoConfiguration
public class AsyncTest {
@Autowired
private AsyncService asyncService;
@Test
public void asyncOne() throws InterruptedException {
System.err.println(asyncService.asyncOne());
Thread.sleep(8000);
}
@Test
public void asyncTwo() throws InterruptedException, ExecutionException {
System.err.println(asyncService.asyncTwo());
}
}
方法执行结果分别如下:
github项目demo地址:https://github.com/LX1309244704/SpringBoot-master/tree/master/springboot-async