异步任务

package com.time.test;
import java.util.concurrent.Future;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import ch.qos.logback.classic.net.SyslogAppender;
@Component
public class AsyncTask {
 
     
 
 @Async
 public  Future<Boolean> doTask11() throws InterruptedException
 {
  long start=System.currentTimeMillis();
  Thread.sleep(1000);
  long end =System.currentTimeMillis();
  System.out.println("任务1耗时"+(end-start)+"毫秒");
  return new AsyncResult<Boolean>(true);
 }
 
 @Async
 public  Future<Boolean> doTask22() throws InterruptedException
 {
  long start=System.currentTimeMillis();
  Thread.sleep(700);
  long end =System.currentTimeMillis();
  System.out.println("任务2耗时"+(end-start)+"毫秒");
  return new AsyncResult<Boolean>(true);
 }
 
 @Async
 public  Future<Boolean> doTask33() throws InterruptedException
 {
  long start=System.currentTimeMillis();
  Thread.sleep(600);
  long end =System.currentTimeMillis();
  System.out.println("任务3耗时"+(end-start)+"毫秒");
  return new AsyncResult<Boolean>(true);
 }
}
 
 
 
 
 
package com.time.test;
import java.util.concurrent.Future;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//异步任务的作用,发送短信,发送邮箱,推送等
@RestController
public class DoTask {
 @Autowired
 private AsyncTask asyncTask;
 
 @RequestMapping("test")
 public String test() throws InterruptedException
 {
  long start=System.currentTimeMillis();
  
  Future<Boolean> a=asyncTask.doTask11();
  Future<Boolean> b=asyncTask.doTask22();
  Future<Boolean> c=asyncTask.doTask33();
 
  while(!a.isDone()||!b.isDone()||!c.isDone())
  {
   if(a.isDone()&&b.isDone()&&c.isDone())
   {
    break;
   }
  }
  
  
  long end=System.currentTimeMillis();
  
  String times="任务全部完成,总耗时"+(end-start)+"毫秒";
  System.out.println(times);
  return times;
 }
 
}
 
 异步任务场景:发送短信,发送邮箱,推送等
 
posted @ 2018-12-23 12:04  远方的人111  阅读(311)  评论(0)    收藏  举报