简体   繁体   English

如何在特定时间内运行Java程序?

[英]How to run a Java program for a specific amount of time?

I want to run my program on a list of files. 我想在文件列表上运行我的程序。 But a few files take much longer than expected time. 但是一些文件花费的时间比预期的时间长得多。 So I want to kill the thread/process after the timeout period, and run the program on next file. 因此,我想在超时时间后终止线程/进程,并在下一个文件上运行程序。 Is there any easy way to do it? 有什么简单的方法吗? I'll be running only one thread at a time. 我一次只运行一个线程。

Edit1: 编辑1:

I am sorry I couldn't make it clear earlier. 对不起,我不能早说清楚。 Here is the for loop code. 这是for循环代码。

for (File file : files)
{
  //Perform operations. 

}

So a file is Java program file which can contain many methods. 因此,文件是Java程序文件,其中可以包含许多方法。 If the number of methods are less, my analysis works fine. 如果方法数量较少,则我的分析效果很好。 If there are many say 20 methods, it keeps executing and analyzing them for a few hours. 如果说有20种方法,它将持续执行和分析几个小时。 So in the latter case, I would like to finish that execution and go for the next java file. 因此,在后一种情况下,我想完成该执行并转到下一个Java文件。

And I don't have any constraint of single threading. 而且我没有单线程的任何约束。 If multi-threading works, it's still good for me. 如果多线程有效,那对我仍然很好。 Thanks. 谢谢。

These kinds of things are usually done multi-threaded. 这些事情通常是多线程完成的。 For an example, see How to timeout a thread . 有关示例,请参见如何使线程超时

As you commented though, you are looking for a single-threaded solution. 正如您所评论的,您正在寻找单线程解决方案。 That is best done by periodically checking if the timeout expired yet. 最好通过定期检查超时是否过期来完成。 Some thread will have to do the checking, and since you requested it to have only one thread, the checking will have to be somewhere halfway in the code. 某些线程将必须执行检查,并且由于您请求它仅具有一个线程,因此检查必须在代码的一半位置进行。

Let's say that the majority of the time spent is in a while-loop that reads the file line-by-line. 假设大部分时间是在while循环中,该循环逐行读取文件。 You could do something like this: 您可以执行以下操作:

long start = System.nanoTime();
while((line = br.readLine()) != null) {
    if(System.nanoTime() - start > 600E9) { //More than 10 minutes past the start.
        throw new Exception("Timeout!");
    }
    ... //Process the line.
}

Just as a quick example of how you would do this using multi-threading: 就像一个使用多线程如何实现的简单示例:

First we make a Runnable for processing the File 首先,我们创建一个Runnable来处理File

class ProcessFile implements Runnable {
    File file;
    public ProcessFile(File file){
        this.file = file;
    }
    public void run(){
        //process the file here
    }
}

Next we actually execute that class as a thread: 接下来,我们实际上将该类作为线程执行:

class FilesProcessor {

    public void processFiles(){
        //I guess you get the files somewhere in here
        ExecutorService executor = Executors.newSingleThreadExecutor();
        ProcessFile process;
        Future future;
        for (File file : files) {
            process = new ProcessFile(file);
            future = executor.submit(process);
            try {
                future.get(10, TimeUnit.MINUTES);
                System.out.println("completed file");
            } catch (TimeoutException e) {
                System.out.println("file processing timed out");
            }
        }
        executor.shutdownNow();
    }
}

So we iterate through each file and process it. 因此,我们遍历每个文件并进行处理。 If it takes longer than 10 minutes, we get a timeout exception and the thread dies. 如果花费的时间超过10分钟,则会收到超时异常,并且线程死亡。 Easy as pie. 易如反掌。

I think you have a while or for loop for processing these files what about reading a timer each loop turn. 我认为您有一段时间或for循环来处理这些文件,那么每次循环读取计时器都会如何。

You can measure how long you are processing data with: 您可以使用以下方法测量处理数据的时间:

 while(....){
       long start = System.currentTimeMillis();
        // ... the code being measured ...    
        long elapsedTime = System.currentTimeMillis() - start;
 }

Or maybe starting chronometer before loop i don't know 或者也许我不知道循环之前启动天文钟

EDIT : So if you have one loop turn by file you have to put somme time measure at some specific point in your code like said darius. 编辑:因此,如果您按文件进行一个循环,则必须在代码中的某些特定点(如darius)放一些时间测量。

For example : 例如 :

   for each file
           start = System.currentTimeMillis();
           //do some treatment
           elapsedTime = System.currentTimeMillis() - start;
           // do a more tratment
           elapsedTime = System.currentTimeMillis() - start;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM