场景需求:
其他应用向我们的应用A发来请求,如果应用A10秒内无处理结果则返回数据未处理完成。
工作简化:
主线程等待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();
}
}
}