java time out,java timeout

场景:Java timeOut的兑现

Java timeOut的实现

用NIO socket读取网络数据,找了好久没找到,NIO下设置读超时的API,只好自己写了一个。

思路是设置守护进程,启动后等待 一定的时间,如果在等待一定的时间后还没被唤醒,则抛出超时异常。

//设置超时守护进程                         TimeOutThread t = new TimeOutThread(5000,new TimeoutException("reading      timeOut"));

t.start();

count=client.read(protocalNum);

count=client.read(functionNum);

count=client.read(messageLen);

messageLen.rewind();

int length = messageLen.asIntBuffer().get(0);

receivebuffer = ByteBuffer.allocate(length-12);

receivebuffer.clear();

count=client.read(receivebuffer);

t.cancel();

notifyAll();

TimeOutThread.java

private long timeOut ;

private boolean isCanceled = false;

private TimeoutException exception;

public TimeOutThread(long timeOut,TimeoutException exception){

super();

this.timeOut = timeOut;

this.exception = exception;

this.setDaemon(true);

}

public synchronized void cancel(){

this.isCanceled = true;

}

public synchronized void  run(){

try{

wait(timeOut);

if(!isCanceled){

throw exception;

}

}

catch(InterruptedException e){

e.printStackTrace();

}

}

TimeOutException.java 就不写了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值