java 模拟实现 timeout 机制
Posted 乔不思
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 模拟实现 timeout 机制相关的知识,希望对你有一定的参考价值。
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();
while(!timeOutThread.isCanceled())
try
sleep(1000);
catch (InterruptedException e)
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(format.format(new Date()));
class TimeoutException extends RuntimeException
public TimeoutException(String msg)
super(msg);
private static final long serialVersionUID = 1L;
@Override
public String toString()
return super.toString();
运行结果:
2016-09-09 18:42:21
2016-09-09 18:42:22
2016-09-09 18:42:23
2016-09-09 18:42:24
Exception in thread "Thread-0" testTimeout.TimeoutException: timout...
at testTimeout.TimeOutThread.run(TimeOutThread.java:39)
2016-09-09 18:42:25
以上是关于java 模拟实现 timeout 机制的主要内容,如果未能解决你的问题,请参考以下文章