public class TimeOutThread extends Thread{
private long timeOut ;
private boolean isCanceled = false;
public long getTimeOut() {
return timeOut;
}
public void setTimeOut(long timeOut) {
this.timeOut = timeOut;
}
public boolean isCanceled() {
return isCanceled;
}
public void setCanceled(boolean isCanceled) {
this.isCanceled = isCanceled;
}
public TimeOutThread(long timeOut){
super();
this.timeOut = timeOut;
this.setDaemon(true);
}
public void cancel(){
this.isCanceled = true;
}
public void run(){
try{
wait(timeOut);
if(!isCanceled){
cancel();
throw new TimeoutException("timout...");
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
TimeOutThread timeOutThread = new TimeOutThread(5000);
timeOutThread.start();
java 模拟实现 timeout 机制
最新推荐文章于 2024-08-16 10:16:08 发布
本文介绍了如何在Java中模拟实现超时(timeout)机制,通过示例代码展示了当操作超过预定时间未完成时,如何抛出TimeoutException。运行结果显示了时间戳以及线程执行的异常情况。
摘要由CSDN通过智能技术生成