So this is my first time using ScheduledFuture and I admit I'm probably way over my head here. I cannot seem to get the below sample to work. Goal is simply to take two sets of actions each with it's own timeout before moving on to the next set and repeating indefinitely.
static ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
ScheduledFuture<?> warm = executor.scheduleWithFixedDelay(() -> {
System.out.println("warmbeans");
//do more stuff here
}, 0, 1000, TimeUnit.MILLISECONDS);
ScheduledFuture<?> cool = executor.scheduleWithFixedDelay(() -> {
System.out.println("coolbeans");
//do more stuff here
}, 0, 500, TimeUnit.MILLISECONDS);
while(true) {
try {warm.get(1000, TimeUnit.MILLISECONDS);}
catch (InterruptedException | ExecutionException | TimeoutException e) {Listen.cancel(true);}
try {cool.get(500, TimeUnit.MILLISECONDS);}
catch (InterruptedException | ExecutionException | TimeoutException e) {Listen.cancel(true);}
Problem is that I keep getting this output:
warmbeans
coolbeans
warmbeans
coolbeans
Exception in thread "Thread-0" java.util.concurrent.CancellationException
at java.util.concurrent.FutureTask.report(FutureTask.java:121)
at java.util.concurrent.FutureTask.get(FutureTask.java:206)
at echoServer.NetworkIO.run(NetworkIO.java:29)
at java.lang.Thread.run(Thread.java:744)
The above referenced line for NetworkIO.java:29 is simply:
try {warm.get(1000, TimeUnit.MILLISECONDS);}
来源:https://stackoverflow.com/questions/30064361/how-to-correctly-use-scheduledexecutorservice