java线程实现超时

java线程实现超时
Javathread
用线程实现超时比较简单,大致思想为:定义一个超时守护线程,改线程启动时就sleep规定的超时时间;再执行一个命令或方法时启动该超时线程,如果该命令或方法在制定时间内执行完毕,则关闭守护线程,否则抛出timeout异常。具体代码如下:

定义一个超时守护线程TimeOutThread:
Java代码 收藏代码

package com.pqrs.file.analyse.timeout;

public class TimeOutThread extends Thread {
/**
* 超时时间
*/
private long timeOut;
/**
* 是否取消
*/
private boolean cancel;
/**
* 自定义超时异常
*/
private TimeOutException timeOutException;

public TimeOutThread(long timeOut, TimeOutException timeOutException){
super();
this.timeOut = timeOut;
this.timeOutException = timeOutException;
//设置本线程为守护线程
this.setDaemon(true);
}

public synchronized void cancel() {
cancel = true;
}

public void run(){
try{
Thread.sleep(timeOut);

if(!cancel){
throw timeOutException;
}
} catch(InterruptedException e){
e.printStackTrace();
}
}
}


定义一个自己的超时异常:
Java代码 收藏代码

package com.pqrs.file.analyse.timeout;

public class TimeOutException extends RuntimeException {
/**
* 序列化号
*/
private static final long serialVersionUID = -8078853655388692688L;

public TimeOutException(String errMessage)
{
super(errMessage);
}
}


测试类:
Java代码 收藏代码

public class TestTimeOut {
public static void main(String a[]){
TimeOutThread timeOutThread = new TimeOutThread(3000, new TimeOutException("time out!"));
try{
timeOutThread.start();
Thread.sleep(5000);
timeOutThread.cancel();
} 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、付费专栏及课程。

余额充值