【问题标题】:How to interrupt a method after specific time in Java?如何在Java中的特定时间后中断方法?
【发布时间】:2020-08-08 22:43:44
【问题描述】:

我需要编写一个简单的程序来打印素数直到给定的数字,但不超过 5 秒。 是否有某种计时器可用于在一段时间后中断方法? (但如果打印时间短于 5 秒,则不会中断)。 提前致谢。

我的代码:

public class Primes {
    private static boolean checkIfPrime(int x) {
        if (x == 2) return true;
        if (x % 2 == 0) return false;
        int sqrt = (int) Math.sqrt(x) + 1;
        for (int i = 3; i < sqrt; i = i + 2) if (x % i == 0) return false;
        return true;
    }

    private static void printPrimesAndOperationTime(int n) {
        long start = System.nanoTime();
        for (int i = 2; i <= n; i++) if (checkIfPrime(i)) System.out.println(i);
        long end = System.nanoTime();

        long timeResult = end - start;
        System.out.println("Printing time = " + timeResult + " [ns] => "
                + Math.round(timeResult * 100.0 / 1000000) / 100.0 + " [ms]");
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();

        printPrimesAndOperationTime(n);
    }
}

【问题讨论】:

标签: java interruption


【解决方案1】:

使用 Java 并发 API 来解决上述问题。请查找用于代码遍历的内联 cmets。

import java.util.Scanner;
import java.util.concurrent.*;

public class TimeoutInterval {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor(); // Start Single thread executor
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        Future future = executor.submit(new Primes(n)); // Find prime no.
        try {
            future.get(5, TimeUnit.SECONDS); // Set the time out of the prime no. search task
            executor.shutdown();
        } catch (TimeoutException e) {
            executor.shutdown();
            System.out.println("Terminated!");
        }

        executor.shutdownNow();
    }
}

class Primes  implements Runnable {
    private final int number;

    Primes(int number) {
        this.number = number;
    }
    @Override
    public void run() {
        System.out.println("Started..");
        printPrimesAndOperationTime(number);
        System.out.println("Finished!");
    }

    private static boolean checkIfPrime(int x) {
        if (x == 2) return true;
        if (x % 2 == 0) return false;
        int sqrt = (int) Math.sqrt(x) + 1;
        for (int i = 3; i < sqrt; i = i + 2) if (x % i == 0) return false;
        return true;
    }

    private static void printPrimesAndOperationTime(int n) {
        long start = System.nanoTime();
        for (int i = 2; i <= n && !Thread.interrupted(); i++) if (checkIfPrime(i)) {
            System.out.println(i);
        }
        long end = System.nanoTime();

        long timeResult = end - start;
        System.out.println("Printing time = " + timeResult + " [ns] => "
                + Math.round(timeResult * 100.0 / 1000000) / 100.0 + " [ms]");
    }

}

【讨论】:

  • 谢谢!现在它在给定时间后中断打印方法。这似乎是我需要的解决方案!
【解决方案2】:

使用 ExecutorService,你可以提交一个超时的任务。在收到 TimeoutException 时,您应该在任务上调用cancel(true) 方法来中断线程。

来自documentation

... 如果任务已经开始,那么 mayInterruptIfRunning 参数确定是否应该中断执行该任务的线程以尝试停止该任务。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 2011-06-04
    相关资源
    最近更新 更多