繁体   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