所以这是我第一次使用ScheduledFuture而且我承认我可能在这里过头了。我似乎无法让下面的示例工作。目标只是采取两组动作,每一组都有自己的超时,然后继续下一组并无限期地重复。
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);}
问题是我一直得到这个输出:
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)
上面引用的NetworkIO.java:29行只是:
try {warm.get(1000, TimeUnit.MILLISECONDS);}