现在的位置: 首页 > 综合 > 正文

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

2018年05月14日 ⁄ 综合 ⁄ 共 907字 ⁄ 字号 评论关闭
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);

抱歉!评论已关闭.