How to correctly use ScheduledExecutorService?

好久不见. 提交于 2019-12-10 10:36:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!