62,567
社区成员




//用一个线程来计时
public Class TimeRecorder implements Runnable throws Exception{
private long startTime;
private long timeCost;
public TimeRecorder(long startTime) {
this.startTime = startTime;
}
public void run() {
while(true) {
timeCost = (System.currentTimeMillis() - startTime)/1000;//Cost Seconds
Thread.sleep(1000);
}
}
public long getTimeCost() {
return this.timeCost;
}
}
public Class MainClass {
....
TimeRecorder timeRecorder = new TimeRecorder(System.currentTimeMillis());
timeRecorder.run();
doSomething(timeRecorder)
....
}
//把计时器传入doSomeThind时间中去,随时检验是否超时
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class Test {
public static void main(String[] args) throws InterruptedException {
final Test t = new Test();
CancelTask.timedRun(new Runnable() {
public void run() {
t.task();
}
}, 3, TimeUnit.SECONDS); // 超时 3 秒
// 超时或者执行完之后
System.out.printf("[%s] ok1... %tF %<tT%n", Thread.currentThread().getName(),
System.currentTimeMillis());
CancelTask.timedRun(new Runnable() {
public void run() {
t.task();
}
}, 2, TimeUnit.SECONDS); // 超时 2 秒
// 超时或者执行完之后
System.out.printf("[%s] ok2... %tF %<tT%n", Thread.currentThread().getName(),
System.currentTimeMillis());
CancelTask.close();
}
public void task() {
// 中断策略:当前线程中断时不再执行了
for(int i = 0; i < 10 && !Thread.currentThread().isInterrupted(); i++) {
doSomething();
}
}
public void doSomething() {
for(int i = 0; i < 1000000000; i++);
System.out.printf("[%s] %tF %<tT%n", Thread.currentThread().getName(), System.currentTimeMillis());
}
}
/**
* 参考 Java Concurrency in Pratice, Listing 7.10
* @author frankiegao123
* 2010-4-14 上午12:17:04
*/
class CancelTask {
private final static ExecutorService taskExec = Executors.newFixedThreadPool(50);
public static void timedRun(Runnable r, long timeout, TimeUnit unit)
throws InterruptedException {
Future<?> task = taskExec.submit(r);
try {
task.get(timeout, unit);
} catch (TimeoutException e) {
// task will be cancelled below
} catch (ExecutionException e) {
throw launderThrowable(e.getCause());
} finally {
task.cancel(true);
}
}
public static RuntimeException launderThrowable(Throwable t) {
if (t instanceof RuntimeException)
return (RuntimeException) t;
else if (t instanceof Error)
throw (Error) t;
else
throw new IllegalStateException("Not unchecked", t);
}
public static void close() {
taskExec.shutdown();
}
}
System.nanoTime() ; 没循环一次都算出他的执行时间,当达到你的期望值时都还没结束for循环,那么终止循环