java 定时调用方法,有结果返回

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 17:34   2550   0
public class MyCallable implements Callable {
    static int num=1;
   // 标志位
   private int flag = 0;
   
   private String resultId="";
   
   public MyCallable(int flag) {
    this.flag = flag;
   }
   public MyCallable(int flag,String resultId) {
  // TODO Auto-generated constructor stub
    this.flag = flag;
    this.resultId=resultId;
 }
   public String call() throws Exception {
    if (this.flag == 0) {
     //如果flag的值为0,则立即返回
     return "flag = 0";
    }
    if(this.flag == 1){
     //如果flag的值为1
      try {
        while(true){
         System.out.println("--------方法----------:"+num);  
         String message="error";
         /**
          *等待查询时间最多为20秒
          */
         Thread.sleep(2000);
         num++;
         if(num==10||!"error".equals(message)){
          return message;
         }
        }
      }catch(InterruptedException e) {
       System.out.println("Interrupted"+e.getMessage());
      }
      return "false";
    }else{
     // falg不为0或者1,则抛出异常
     throw new Exception("Bad flag value!");
    }
   }
}


调用:

         MyCallable task=new MyCallable(1, result);
         //创建一个执行任务的服务
         ExecutorService es = Executors.newFixedThreadPool(3);
         Future future = es.submit(task);
         String message=(String) future.get();
         //关闭任务
         future.cancel(true);


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP