Guarded Timed 处理超时的异常

很好地时间超时,处理异常的方法,在蓝牙搜索时,如果超时,时间过长,在设备性能不好的前提下,很难catch到异常,自己手动写一个处理超时的异常,防止界面卡死。

首先定义一个TimeoutException:

public class TimeoutException extends InterruptedException {
public TimeoutException(String msg) {
super(msg);
}
}
 
Host:
拥有更改状态用的setExecutable方法与执行用的executable方法。
public class Host {
private final long timeout; // timeout值  
private boolean ready = false; //如果可以执行的话为true
public Host(long timeout) {
this.timeout = timeout;
}
// 更改状态
public synchronized void setExecutable(boolean on) {
ready = on;
notifyAll();
}
 
public synchronized void execute() throws InterruptedException,
TimeoutException
{
long start = System.currentTimeMillis(); //开始时刻
while (!ready) {
long now = System.currentTimeMillis(); //现在时刻
long rest = timeout - (now - start); //剩余的时间
if (rest <= 0) {
throw new TimeoutException("now - start = " + (now - start) + ", timeout = " + timeout);
}
wait(rest);
}
doExecute();
}
// 实际的处理动作  
private void doExecute() {
System.out.println(Thread.currentThread().getName() + " calls
doExecute");
}
}
Main:
public class Main {
public static void main(String[] args) {
Host host = new Host(10000); //等待10秒钟
try {
System.out.println("execute BEGIN");


host.execute();
} catch (TimeoutException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值