How to stop execution after a certain time in Java?

后端 未结 4 1469
攒了一身酷
攒了一身酷 2020-11-28 07:01

In the code, the variable timer would specify the duration after which to end the while loop, 60 sec for example.

   while(timer) {
    //run
    //terminate         


        
4条回答
  •  一个人的身影
    2020-11-28 07:22

    you should try the new Java Executor Services. http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

    With this you don't need to program the loop the time measuring by yourself.

    public class Starter {
    
        public static void main(final String[] args) {
            final ExecutorService service = Executors.newSingleThreadExecutor();
    
            try {
                final Future 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();
            }
        }
    }
    
        

    提交回复
    热议问题