2

所以这是我第一次使用 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);}
4

0 回答 0