JAVA:如果持续时间超过1秒,如何中断功能

时间:2013-07-03 16:08:15

标签: java time interrupt

我的程序中有这样的代码

for(int i = 0; i < 100000; i++) {
    func(i);
}

对于i的大多数值,func持续时间不到1秒,但对于某些值,它可能持续几分钟,所以如果持续时间太长,我需要打断它。

我该怎么做?

5 个答案:

答案 0 :(得分:1)

FutureTask非常适合执行超时代码。

    FutureTask task = new FutureTask(new Callable() {
        @Override
        public Object call() throws Exception {
            /* Do here what you need */
            return null; /* Or any instance */
        }
    }) {
    };
    try {
        Object result = task.get(1, TimeUnit.SECONDS);
    } catch (InterruptedException ex) {
        Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ExecutionException ex) {
        Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TimeoutException ex) {
        Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
    }
}

答案 1 :(得分:0)

中断可能需要太长时间的函数的一种方法是在单独的线程中运行它。然后,您可以在一秒钟后向该线程发送一条消息,告诉它停止。不使用线程,您可以通过使用以下代码替换func来处理它:

function process(int i, long maxMiliseconds) {
    long start = System.currentTimeMillis();
    while(System.currentTimeMillis() - start < maxMiliseconds) {
        //do your processing one step at a time
        // return an answer if you have one.
    }
    //make some record of the fact that the process timed out for i.
    return;
}

答案 2 :(得分:0)

你可以在一个单独的线程中启动func(),然后在你的线程上执行方法join(long millis),等待1秒钟结束。但是线程仍会运行直到完成(不推荐使用stop()方法)。这样做的方法是控制当前线程并做出适当的反应

答案 3 :(得分:0)

这就是我看到它的方式。我确信有很多方法可以用更少的代码来完成,但这个方法是直截了当的解决方案

如果您想在func(i);中运行Thread,那么这将是另一个故事。

public class MainClass {
    private static boolean riding, updated = false;


    private static int timeout = 10000;

    public static void main(String[] args) {
        while (true) {
            if (!riding){
                long endTimeMillis = System.currentTimeMillis() + timeout;
                func(endTimeMillis);
            }
        }
    }

    private static void func(long endTimeMillis) {
        for (int i = 0; i < 9999; i++) {
            if ((!riding && System.currentTimeMillis() < endTimeMillis) || updated) {
                updated = false;
                System.out.println("run method main function");
                riding = true;
            } else {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(System.currentTimeMillis() + " > "
                        + endTimeMillis);
                if (System.currentTimeMillis() > endTimeMillis) {
                    updated = true;
                    System.out.println("overdue");
                    riding = false;
                    break;
                }
            }
        }
        riding = false;
    }
}

答案 4 :(得分:0)

如果您不想要其他线程,可以将异常处理注入func。

  public static void main(String[] args)
{


        try 
        {
           func(1);
        } 
        catch (timeR e) 
        {
             System.out.println("enough!")
             // TODO Auto-generated catch block
             e.printStackTrace();

        }

}


    static void func(int a) throws timeR //your func needs to throw something when time-is-up
    {
       long time1,time2;             //reference time and current time
       time1=System.nanoTime();      //having reference
       time2=System.nanoTime();      //init of current
       while(true)                   //You did not put your func, so I used inf-while
       {
            //here whatever your func does,
                //.....
                //.....
            //below line checks if time is up
            time2=System.nanoTime();
            if((time2-time1)>1000000000)   //1000000000 is 1 second or 1Billion nanoseconds
            { throw new timeR("time is up!");} 
            //this is throwing(an alternative exit from this function)
       }

    }

    static class timeR extends Exception
    {
      //Parameterless Constructor

       public timeR() 
       {

       }

       //Constructor that accepts a message
       public timeR(String message)
       {
          super(message);
       }
    }

输出:在func()之后1秒调用:

enough!
proje.lineerCebir$timeR: time is up!
at proje.lineerCebir.func(lineerCebir.java:198)
at proje.lineerCebir.main(lineerCebir.java:179)

也许你不想看到红色消息,然后只注释掉e.printStackTrace()。 玩得开心。