【问题标题】:Terminate Java Program after time expired超时后终止 Java 程序
【发布时间】:2018-04-23 18:44:56
【问题描述】:

我正在做我的算法作业。 我写了下面的代码,但是如果时间到期我必须停止它。 时间限制为 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());

}
}

【问题讨论】:

  • Java 不喜欢异步外部中断。如果您想在一段时间后终止您的程序(以及它的每个线程,如果是多线程的)必须定期检查时间是否已过期。有很多方法可以做到这一点。

标签: java sorting time merge insertion-sort


【解决方案1】:

如果您使用的是 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 2014-04-22
    • 2018-03-03
    • 2015-09-05
    • 2019-04-23
    • 2011-09-26
    • 2020-09-03
    相关资源
    最近更新 更多