OnJava8-Examples/onjava/TimedAbort.java

31 lines
836 B
Java
Raw Normal View History

// onjava/TimedAbort.java
// (c)2021 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2017-01-23 08:19:11 -08:00
// Terminate a program after t seconds
package onjava;
2017-01-11 16:18:57 -08:00
import java.util.concurrent.*;
2015-06-15 17:47:35 -07:00
public class TimedAbort {
2017-01-21 16:29:16 -08:00
private volatile boolean restart = true;
2017-01-23 08:19:11 -08:00
public TimedAbort(double t, String msg) {
2017-01-11 16:18:57 -08:00
CompletableFuture.runAsync(() -> {
2017-01-21 16:29:16 -08:00
try {
while(restart) {
restart = false;
2017-01-23 08:19:11 -08:00
TimeUnit.MILLISECONDS
.sleep((int)(1000 * t));
2017-01-21 16:29:16 -08:00
}
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
2017-01-12 16:49:36 -08:00
System.out.println(msg);
2017-01-11 16:18:57 -08:00
System.exit(0);
});
2015-06-15 17:47:35 -07:00
}
2017-01-23 08:19:11 -08:00
public TimedAbort(double t) {
this(t, "TimedAbort " + t);
2017-01-12 16:49:36 -08:00
}
2017-01-21 16:29:16 -08:00
public void restart() { restart = true; }
2015-09-07 11:44:36 -06:00
}