时间到期后终止Java程序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了时间到期后终止Java程序相关的知识,希望对你有一定的参考价值。

我正在做我的算法作业。我写了下面的代码,但是如果时间到期我必须停止它。时间限制是10分钟。我该怎么写呢?我必须使用什么样的界面或类?我试图在网上寻找一些东西,但没有什么可以帮助我。我看到有人使用了Runnable接口,其他人使用了其他类型的方法,但正如我之前所说,没有什么可以帮助我。

package sortUsage;
import sorting.SortingArrayException;
import sorting.Sorting;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class SortUsage 
{
private static final Charset ENCODING = StandardCharsets.UTF_8;

private static void printSortedArray(Sorting<Record> sorting, int choice)throws SortingArrayException
{
    Record currentRecord = null;
    ArrayList<Record> array = new ArrayList<>(sorting.size());

    switch(choice)
    {
        case 1:
            array = sorting.getArrayList();
            sorting.mergeSortArrayList();
        break;

        case 2:
            array = sorting.getArrayList();
            array = sorting.insertionSort(array);
        break;
    }

    System.out.println("
Sorted Array of records
");
    for(int i = 0; i < sorting.size(); i++)
    {
        currentRecord = array.get(i);
        System.out.println(currentRecord.getIntegerField() + "	" + i);
    }
}

private static void loadArray(String filePath, Sorting<Record>sorting) throws IOException,SortingArrayException
{
    System.out.println("
Loading data into array...
");
    Path inputFilePath = Paths.get(filePath);

    try(BufferedReader fileInputReader = Files.newBufferedReader(inputFilePath,ENCODING))
    {
        String line = null;
        // lineNumber = 0;
            while((line = fileInputReader.readLine()) != null && !line.isEmpty())
            {
                String[] lineElements = line.split(",");
                Record record1 = new Record(Long.parseLong(lineElements[0]));
                //System.out.println(lineNumber);
                //lineNumber++;
                sorting.add(record1);
            }
    }
    System.out.print("Data loaded
");
}

 private static void testWithComparisonFunction(String filepath, int choice, Comparator<Record> comparator) throws IOException,FileNotFoundException, SortingArrayException
 {
     Sorting<Record> sorting = new Sorting<>(comparator);
     loadArray(filepath,sorting);
     printSortedArray(sorting,choice);      
}

@SuppressWarnings("resource")
public static void main(String[] args) throws IOException,SortingArrayException,Exception
{
    Scanner input = new Scanner (System.in);
    int choice;
    do
    {
        System.out.println("1) MERGE SORT;
2) INSERTION-SORT;");
        System.out.print("Inserisci il tipo di ordinamento desiderato: ");
        choice= input.nextInt();
    }while(choice != 1 && choice != 2);

    String path = "src/files/integers.csv";//my File Path
    testWithComparisonFunction(path, choice, new RecordComparatorIntField());

}
}
答案

如果您使用的是Java 8,则可以使用ThreadPool执行程序来实现此目的。重构您的代码以在线程中执行,然后将其提交给ExecutorServiceto执行它,指定要完成的超时。像这样:

public List<PublishResult> publishArticles(List<Article> articles) throws InterruptedException, ExecutionException {

ExecutorService executorService = Executors.newSingleThreadExecutor();

return articles.stream()
        .map(article -> {

            Future<PublishResult> task = executorService.submit(() -> publisher.publish(article));

            try {
                return task.get(10, TimeUnit.SECONDS);
            } catch (InterruptedException | ExecutionException | TimeoutException e) {
                return PublishResult.FAILED(article);
            }
        })
        .collect(Collectors.toList());
}

你可以找到更多here

以上是关于时间到期后终止Java程序的主要内容,如果未能解决你的问题,请参考以下文章

Java:抛出异常后如何终止执行后面的代码?

Java:抛出异常后如何终止执行后面的代码?

在片段活动中显示自定义对话框

做个日期查询,判断开始日期与终止日期范围必须在一个月之内,用java代码

片段中的 Asynctask 未到达 onPostExecute

JAVA怎样终止代码的执行?