时间到期后终止Java程序

时间:2018-04-23 18:44:57

标签: java sorting time merge insertion-sort

我在做算法作业。 我写了下面的代码,但是如果时间到期我必须停止它。 时间限制是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("\nSorted Array of records\n");
    for(int i = 0; i < sorting.size(); i++)
    {
        currentRecord = array.get(i);
        System.out.println(currentRecord.getIntegerField() + "\t" + i);
    }
}

private static void loadArray(String filePath, Sorting<Record>sorting) throws IOException,SortingArrayException
{
    System.out.println("\nLoading data into array...\n");
    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\n");
}

 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;\n2) 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());

}
}

1 个答案:

答案 0 :(得分:0)

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

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