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 机制
最新推荐文章于 2022-07-27 16:26:25 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)