java时间控制

sling2007 2010-04-13 09:59:16
我用到一个for循环
for(int i=0;i<10;i++){
dosomething();
}

其中dosomething()可能耗费很多时间,而且可能一直运行不完,
我想知道怎么样可以给这个循环加一个时间限制
使它执行时间过长的时候,直接来一个break或者continue


...全文
316 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
Martual 2011-05-12
  • 打赏
  • 举报
回复
我也想知道答案~ 继续跟踪~
samanthazl 2010-04-22
  • 打赏
  • 举报
回复
不好意思,,拿个分。谢谢
Dazzlingwinter 2010-04-22
  • 打赏
  • 举报
回复

//用一个线程来计时
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时间中去,随时检验是否超时
sling2007 2010-04-22
  • 打赏
  • 举报
回复
“dosomething()可能耗费很多时间,而且可能一直运行不完”,
所以这个计时线程是不是应该在dosomething中?
因为如果“
Thread.start();
dosomething();
Thread.interrupt();

”的话,dosomething还是在顺序执行,不能顺利跳出循环啊。
sling2007 2010-04-22
  • 打赏
  • 举报
回复
是不是只好用thread了??????????????
各位
  • 打赏
  • 举报
回复
最关键的决定是中断策略。也就是说如果达到超时间,那那些任务是执行完,还是中断?如果是中断的话,只要在运行中的任务是不可能被中断的,因此需要在任务的地方加入中断策略。

参考代码:

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();
}
}
liujun3512159 2010-04-14
  • 打赏
  • 举报
回复
路过,来接分
marf_cn 2010-04-14
  • 打赏
  • 举报
回复
可以单独写个线程,在dosomething之前运行,记下当时的currentTime,线程的run 里面设置判断一个最大时间,超过时间就中断
James.Ji 2010-04-14
  • 打赏
  • 举报
回复
问题是其中dosomething()可能耗费很多时间,而且可能一直运行不完,所以必须在dosomething内设置中断响应,单单在for中做响应也是会有很大延迟的
zfq642773391 2010-04-14
  • 打赏
  • 举报
回复
for(int i=0;i<10;i++){
Thread.start();
dosomething();
Thread.interrupt();
}
写个 计时的线程,在dosomething前运行,计算运行时间,当时间大于你设定的值时,跳出
soooooga 2010-04-13
  • 打赏
  • 举报
回复
System.nanoTime() ; 没循环一次都算出他的执行时间,当达到你的期望值时都还没结束for循环,那么终止循环
hjjk123 2010-04-13
  • 打赏
  • 举报
回复



Thread.sleep()??

62,624

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧