1.启动类开启注解
@EnableAsync
//asyncTaskService(异步服务类)
@Async
public Future<Long> Counter(){
long count = 0;
try{
count ++;
}catch (Exception e){
log.error(e.getMessage(),e);
}
return new AsyncResult<Long>(count);
}
//业务代码使用
Future futureDay = asyncTaskService.Counter();
long dayNum = (long)futureDay.get();
@Async ( "taskExecutor" ) public Future < String > run () throws Exception {
long sleep = random . nextInt ( 10000 );
log . info ( "开始任务,需耗时:"+sleep+"毫秒" );
Thread.sleep( sleep );
return new AsyncResult <>( "test" );
}
//测试
Future < String > futureResult = task . run ();
String result = futureResult.get( 5 , TimeUnit. SECONDS );