private static class ExpiringThread extends Thread { TimedRunnable timed; long expired; ExpiringThread(TimedRunnable task, long expiredTime) { timed = task; expired = expiredTime; } public void run() { try { Thread.sleep(expired); } catch (InterruptedException e) { e.printStackTrace(); } timed.expire(); } } public static void execute(TimedRunnable task, long expiredTime) { new Thread(task).start(); new ExpiringThread(task, expiredTime).start(); } }下面是一个测试程序,该程序实现了TimedRunnable接口,也就是说它愿意被执行超时控制。 可以看到,任务在超时的时候会停止自己,这个逻辑是任务自身定义的(用一个expired标志变量)。 expire()方法还给了任务在超时的时候执行更多清理工作的灵活性,比如关闭流和数据库连接等等。public class ExpiringTest implements TimedRunnable { private boolean expired; public void run() { while (!expired) { try { System.out.println("I'm still running..."); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("expired!"); } public synchronized void expire() { expired = true; } public static void main(String[] args) { TimedTaskExecuter.execute(new ExpiringTest(), 1000); }}
当然也可以为所有超时任务定义一个抽象的超类TimedTask:public abstract class TimedTask implements TimedRunnable { private boolean expired; public synchronized void expire() { expired = true; }}任何类只要继承TimedTask,就自动具有超时逻辑。当然,如果覆盖了expire()方法,则必须调用super.expire()。
import java.util.Date; public class Test { public static void main(String[] args) { Test test = new Test() ; try { test.fun() ; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void fun() throws Exception{ Date d1 = new Date() ; for(int i=0 ; i<100000 ; i++){ System.out.println(i); if((new Date().getTime()-d1.getTime())>100){
throw new Exception("方法运行超时");
} } } } 这样是可以不知道楼主嫌弃不
来个笨方法,呵呵 public static void main(String[] args) { long past = new Date().getTime(); System.out.println("wait 10 sec...."); while (true) { if (new Date().getTime() - past > 10000) { break; } } System.out.println("10 sec is past"); }
/** * @author bzwm * */ public class MethodTimeOut { public static void main(String args[]){ Executer e = new Executer("obj->bzwm");
java.util.TimerTask;
LZ看看这2个类 很简单的哇 一看就肯定会的
import java.util.TimerTask;public class test1 {
private final Timer timer = new Timer();
private final int minutes;
public test1 (int minutes) {
this.minutes = minutes;
}
public void start() {
timer.schedule(new TimerTask() {
public void run() {
TimesUp();
timer.cancel();
}
private void TimesUp() {
System.out.println("test11111");
//这里LZ想干嘛干嘛
// System.gc();
}
}, minutes * 60 * 1000);
}
public static void main(String[] args) {
test1 Timer = new test1(1);
Timer.start();
}
}
runWithTimeout();
} public static void runWithTimeout() throws TimeoutException {
FutureTask<Object> task = new FutureTask<Object>(new Callable<Object>(){ public Object call() throws Exception {
//TODO 调用你的方法
Thread.sleep(1500);
return null;
} });
try {
Object result = task.get(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
//超时
throw e;
}
}
在程序结束时打一下当前时间的毫秒数
if(差值>10000){
抛异常
}
程序似乎根本就不执行call()里面的代码~~~
一下的文章就是在Java中实现类似的功能.文章很长,慢慢看.
http://www.ddj.com/java/184410467
接口中定义一个方法expire(),该方法被控制线程在判断该任务超时的时候调用:public interface TimedRunnable extends Runnable {
void expire();
}下面设计控制类TimedTaskExecuter,该类有一个静态方法execute(),用来执行超时任务。
同时在类内部定义一个嵌套类ExpiringThread,它就是控制超时的线程,继承自Thread。
控制类的execute()方法中启动两个线程,一个是任务线程,一个是控制超时的线程。控制超时的线程会sleep一定时间,任务线程被限制在这个时间之前完成。一旦控制线程被唤醒,就会调用任务线程的expire()方法,这也就意味着任务超时。
当然,控制线程并没有真正去停止任务任程,只是调用了它的一个方法expire()。它告诉任务线程,必须在expire()这个方法中设法停止自己。public class TimedTaskExecuter {
private static class ExpiringThread extends Thread {
TimedRunnable timed;
long expired;
ExpiringThread(TimedRunnable task, long expiredTime) {
timed = task;
expired = expiredTime;
}
public void run() {
try {
Thread.sleep(expired);
} catch (InterruptedException e) { e.printStackTrace(); }
timed.expire();
}
} public static void execute(TimedRunnable task, long expiredTime) {
new Thread(task).start();
new ExpiringThread(task, expiredTime).start();
}
}下面是一个测试程序,该程序实现了TimedRunnable接口,也就是说它愿意被执行超时控制。
可以看到,任务在超时的时候会停止自己,这个逻辑是任务自身定义的(用一个expired标志变量)。
expire()方法还给了任务在超时的时候执行更多清理工作的灵活性,比如关闭流和数据库连接等等。public class ExpiringTest implements TimedRunnable { private boolean expired; public void run() {
while (!expired) {
try {
System.out.println("I'm still running...");
Thread.sleep(100);
} catch (InterruptedException e) { e.printStackTrace(); }
}
System.out.println("expired!");
} public synchronized void expire() {
expired = true;
} public static void main(String[] args) {
TimedTaskExecuter.execute(new ExpiringTest(), 1000);
}}
expired = true;
}}任何类只要继承TimedTask,就自动具有超时逻辑。当然,如果覆盖了expire()方法,则必须调用super.expire()。
public class Test {
public static void main(String[] args) {
Test test = new Test() ;
try {
test.fun() ;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void fun() throws Exception{
Date d1 = new Date() ;
for(int i=0 ; i<100000 ; i++){
System.out.println(i);
if((new Date().getTime()-d1.getTime())>100){
throw new Exception("方法运行超时");
}
}
}
}
这样是可以不知道楼主嫌弃不
public static void main(String[] args) {
long past = new Date().getTime();
System.out.println("wait 10 sec....");
while (true) {
if (new Date().getTime() - past > 10000) {
break;
}
}
System.out.println("10 sec is past");
}
/**
* @author bzwm
*
*/
public class MethodTimeOut {
public static void main(String args[]){
Executer e = new Executer("obj->bzwm");
e.start();
try {
e.join(1000);
} catch (InterruptedException e1) {
System.out.println(e.toString());
}
e.interrupt();
System.out.println(e.isOver());
}
}class Executer extends Thread{
private Object obj = null;
private boolean isOver = false;
public Executer(Object o){
obj = o;
}
public void run(){
doSomething();
}
private void doSomething(){
System.out.println("Start do something with " + obj);
try {
sleep(1500);
} catch (InterruptedException e) {
}
System.out.println("do something with " + obj + " over");
isOver = true;
}
public boolean isOver(){
return isOver;
}
}
这样行吗
[ run() 运行完时,记得一定要改变 isFinished() 所表示的运行状态。] public static void g(NewInterface obj) throws Exception {
Thread t = new Thread(obj);
t.start();
t.join(3 * 1000);
if (!obj.isFinished()) {
obj.interrupt();
throw new Exception();
}
} public interface NewInterface extends Runnable { boolean isFinished(); void interrupt();
}
呵呵,上面引用这位兄弟理解错了,他的意思是:在你的代码里中的
System.out.println("I'm still running...");
这行就就执行了N久,你咋怎么办啊?遇到同样的问题,今天看到这个帖子看了半天。。