Change delay time to double

This commit is contained in:
Bruce Eckel 2017-01-23 08:19:11 -08:00
parent 04039c7b6a
commit 840f7bad3c
2 changed files with 10 additions and 22 deletions

View File

@ -6,28 +6,15 @@ package onjava;
import java.util.concurrent.*; import java.util.concurrent.*;
public class Nap { public class Nap {
// Seconds: public Nap(double t) { // Seconds
public Nap(int n) {
try { try {
TimeUnit.SECONDS.sleep(n); TimeUnit.MILLISECONDS.sleep((int)(1000 * t));
} catch(InterruptedException e) { } catch(InterruptedException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
// Fractions of a second: public Nap(double t, String msg) {
public Nap(double d) { this(t);
try {
TimeUnit.MILLISECONDS.sleep((int)(1000 * d));
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
}
public Nap(int n, String msg) {
this(n);
System.out.println(msg);
}
public Nap(double d, String msg) {
this(d);
System.out.println(msg); System.out.println(msg);
} }
} }

View File

@ -2,18 +2,19 @@
// (c)2017 MindView LLC: see Copyright.txt // (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information. // Visit http://OnJava8.com for more book information.
// Terminate a program after n seconds // Terminate a program after t seconds
package onjava; package onjava;
import java.util.concurrent.*; import java.util.concurrent.*;
public class TimedAbort { public class TimedAbort {
private volatile boolean restart = true; private volatile boolean restart = true;
public TimedAbort(int n, String msg) { public TimedAbort(double t, String msg) {
CompletableFuture.runAsync(() -> { CompletableFuture.runAsync(() -> {
try { try {
while(restart) { while(restart) {
restart = false; restart = false;
TimeUnit.SECONDS.sleep(n); TimeUnit.MILLISECONDS
.sleep((int)(1000 * t));
} }
} catch(InterruptedException e) { } catch(InterruptedException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
@ -22,8 +23,8 @@ public class TimedAbort {
System.exit(0); System.exit(0);
}); });
} }
public TimedAbort(int n) { public TimedAbort(double t) {
this(n, "TimedAbort " + n); this(t, "TimedAbort " + t);
} }
public void restart() { restart = true; } public void restart() { restart = true; }
} }