java 接口方法超时异常处理 设置超时时间
文章目录
原文:https://blog.csdn.net/coding\_1994/article/details/87728374
使用线程池另起一个线程,可以使用 newFixedThreadPool() 也可以使用 newSingleThreadExecutor();具体的这两个线程池如何使用自行百度或者去编程思想看看。
public class InterfaceTimeOut{
public static void main(String args[]){
final ExecutorService exec = Executors.newSingleThreadExecutor();
Callable<String> call = new Callable<String>(){
@Ovrride
public String call() throws Exception{
Thread.sleep(1000 * 5);
return "线程执行完";
}
};
Future<String> future = exec.submit(call);
String obj = null;
try{
obj = future.get(1000 * 6,TimeUnit.MILLISECONDS);
System.out.print("任务成功返回"+obj);
}catch(InterruptedException e){
e.printStackTrace();
}catch(ExecutionException e){
e.printStackTrace();
}catch(TimeoutException e){
e.printStackTrace();
}
exec.shutdown();
}
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册⭐️ Admin快速开发: https://show.cool-admin.com/
赞 0⭐️ 官方文档: https://cool-js.com
赞 0⭐️ chatgpt在线体验: https://cool-js.com/ai/chat-vip/index.html?r=helloworld
赞 0