主线程等待10秒钟,无应答返回(一)

 
场景需求:
其他应用向我们的应用A发来请求,如果应用A10秒内无处理结果则返回数据未处理完成。
工作简化:
主线程等待10秒钟,如果子线程没有完成工作,则日志标识。
下面是代码实现:
import java.util.Random;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PrivateAccount implements Callable<Integer> {
 
 protected static   final  Logger logger = LoggerFactory.getLogger(PrivateAccount.class); 
 
 long timework = 1;
 
 
 public PrivateAccount(long timework) {
  super();
  this.timework = timework;
 }
 public Integer call() throws Exception {
  //sleep单位毫秒
  logger.info("这里是子线程,开始工作,工作需要大约{}秒钟",this.timework);
  Thread.sleep(this.timework*1000);  
  Integer  totalMoney = new Integer(new Random().nextInt(10000));  
  logger.info("这里是子线程,工作完成");
        return  totalMoney ; 
 } 
}

 



import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 要求:
 *  实现一种效果测试。主线程等待工作线程完成任务并获取结果,如果1分钟内没有获取结果,则告知获取失败
 * 实现方式:
 * FutureTask
 */
public class Demo1Main {
 protected static   final  Logger logger = LoggerFactory.getLogger(Demo1Main.class); 
 public static void main(String[] args) {
  //设定子线程工作时间
  long  subThreadWorkTime = 9;
        Callable<Integer> pAccount = new PrivateAccount(subThreadWorkTime); 
        //注意使用类:FutureTask
        FutureTask<Integer> futureTask = new FutureTask<Integer>(pAccount);  
        // 使用futureTask创建一个线程  
        Thread pAccountThread = new Thread(futureTask);
        long  timeout = 8 ;
        logger.info("主线程:设定等待时间是:{}秒" , timeout);
        
        pAccountThread.start();  
        try {
   Integer result =  futureTask.get(timeout, TimeUnit.SECONDS);
   logger.info("{}秒钟工作完成,响应结果是:{}",timeout,result);  
  } catch (InterruptedException | ExecutionException | TimeoutException e1) {
   if (e1 instanceof  TimeoutException){
    logger.info("{}秒钟没有响应结果,系统退出",timeout);  
   }else{
     
    e1.printStackTrace();
   }
   pAccountThread.interrupt();
   
  }
 }
}




 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值