比如说我希望某一方法的执行时间不超过10秒钟
如果超过这个时间,程序退出或者抛出异常
这个功能如何实现?

解决方案 »

  1.   

    java.util.Timer;
    java.util.TimerTask;
    LZ看看这2个类 很简单的哇 一看就肯定会的
      

  2.   

    import java.util.Timer;
    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();
           
        }
    }
      

  3.   

    public static void main(String[] args) throws TimeoutException {
    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;
    }
    }
      

  4.   

    public void schedule(TimerTask task,long delay)  安排在指定延迟后执行指定的任务。 而我只是想做一个方法执行超时的判断,跟我的要求好像不符噢
      

  5.   

    在程序开始时打一下当前时间的毫秒数
    在程序结束时打一下当前时间的毫秒数
    if(差值>10000){
       抛异常
    }
      

  6.   

    五楼的代码我试了下
    程序似乎根本就不执行call()里面的代码~~~
      

  7.   

    VC里面经常使用WaitForSingleObject(....)实现同步.
    一下的文章就是在Java中实现类似的功能.文章很长,慢慢看.
    http://www.ddj.com/java/184410467
      

  8.   

    用一个线程去停止另一个线程是不安全的,Java中不建议这样做,所以线程的stop()方法是deprecated的。线程应该自己终止自己,即退出run()方法的执行。对这个问题有一个实现方法就是,让想要被超时控制的任务自己去定义自己的超时条件,这样,控制超时的线程不需要深入被控制线程的内部就可以把该线程定为已超时。超时以后要执行的具体代码由被控制任务自己定义。首先为一个想要被超时控制的任务定义一个接口TimedRunnable,该接口继承自Runnable,即它可以做为单独线程来运行。
    接口中定义一个方法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);
    }}
      

  9.   

    当然也可以为所有超时任务定义一个抽象的超类TimedTask:public abstract class TimedTask implements TimedRunnable {    private boolean expired;    public synchronized void expire() {
            expired = true;
        }}任何类只要继承TimedTask,就自动具有超时逻辑。当然,如果覆盖了expire()方法,则必须调用super.expire()。
      

  10.   

    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("方法运行超时");

    }
    }
    }
    }
    这样是可以不知道楼主嫌弃不
      

  11.   

    来个笨方法,呵呵
    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");
    }
      

  12.   


    /**
     * @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;
    }
    }
    这样行吗
      

  13.   

    不知道符不符合你的要求
    [ 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();
        }
      

  14.   

    09年的帖子,也得回复一下,免得后面的兄弟再误入歧途,
    呵呵,上面引用这位兄弟理解错了,他的意思是:在你的代码里中的
    System.out.println("I'm still running...");
    这行就就执行了N久,你咋怎么办啊?遇到同样的问题,今天看到这个帖子看了半天。。
      

  15.   

    这是一个standard java无法解决的问题使用asynchronized可以绝决这个问题  不过这个包需要在real-time Java里面找到http://java.sun.com/javase/technologies/realtime/index.jsp
      

  16.   

    specify the solution: The Asynchronous transfer of control. aka ATCGOOD LUCK!