簡體   English   中英

如何在Java中的一段時間后停止執行?

[英]How to stop execution after a certain time in Java?

在代碼中,變量計時器將指定結束while循環的持續時間,例如60秒。

   while(timer) {
    //run
    //terminate after 60 sec
   }
long start = System.currentTimeMillis();
long end = start + 60*1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < end)
{
    // run
}

您應該嘗試新的Java Executor服務。 http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

有了這個,你不需要自己編程循環時間。

public class Starter {

    public static void main(final String[] args) {
        final ExecutorService service = Executors.newSingleThreadExecutor();

        try {
            final Future<Object> f = service.submit(() -> {
                // Do you long running calculation here
                Thread.sleep(1337); // Simulate some delay
                return "42";
            });

            System.out.println(f.get(1, TimeUnit.SECONDS));
        } catch (final TimeoutException e) {
            System.err.println("Calculation took to long");
        } catch (final Exception e) {
            throw new RuntimeException(e);
        } finally {
            service.shutdown();
        }
    }
}

如果你不能超過你的時間限制(這是一個硬限制),那么線程是你最好的選擇。 一旦達到時間閾值,就可以使用循環來終止線程。 當時該線程中發生的任何事情都可能被中斷,允許計算幾乎立即停止。 這是一個例子:

Thread t = new Thread(myRunnable); // myRunnable does your calculations

long startTime = System.currentTimeMillis();
long endTime = startTime + 60000L;

t.start(); // Kick off calculations

while (System.currentTimeMillis() < endTime) {
    // Still within time theshold, wait a little longer
    try {
         Thread.sleep(500L);  // Sleep 1/2 second
    } catch (InterruptedException e) {
         // Someone woke us up during sleep, that's OK
    }
}

t.interrupt();  // Tell the thread to stop
t.join();       // Wait for the thread to cleanup and finish

這將使你的解決方案大約1/2秒。 通過在while循環中更頻繁地輪詢,可以降低它。

你的runnable的運行看起來像這樣:

public void run() {
    while (true) {
        try {
            // Long running work
            calculateMassOfUniverse();
        } catch (InterruptedException e) {
            // We were signaled, clean things up
            cleanupStuff();
            break;           // Leave the loop, thread will exit
    }
}

根據Dmitri的回答更新

Dmitri指出了TimerTask ,它可以讓你避免循環。 你可以只進行連接調用,你設置的TimerTask將負責中斷線程。 這樣可以讓您獲得更精確的分辨率,而無需循環輪詢。

取決於while循環正在做什么。 如果它有可能會長時間阻塞,請使用TimerTask來安排任務設置stopExecution標志,並使用.interrupt()你的線程。

只有循環中的時間條件,它可以永遠坐在那里等待輸入或鎖定(然后再次,可能不是你的問題)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM