开发者

Return statement while using worker thread

Do I always have to return something using Worker Thread in Swing? What if I don't have any return value?开发者_StackOverflow社区 I just want to use the worker thread to run an infinite for loop... so what to return? and even if I write a dummy return statement after the infinite for loop, say for e.g return 0; then also it will probably say "code not reachable".


I suspect you haven't tried it. The code you've suggested in the comment should work fine:

public Object construct() {
  for (;;) {
    Node.execution();
    Clock.incrementTimeTick();
    System.out.println(Clock.getTimeInTick());
    repaint();
  }
  // End of loop is unreachable, so no need for a return statement.
}

A tight loop like this seems like a bad idea to me, and the repaint() code will need to be made appropriately thread-safe, but it should compile...

Personally I prefer to use while (true) for "forever" loops, but for (;;) should work too.


Implement the worker as SwingWorker<Void, SomeObject> and just return null. Trick the compiler about the infinite loop. Make it depending on some method that in the runtime always return true.


A method like the follow will compile without any compilation errors:

public Object foo() {
    for (;;) {
        // do something ... or nothing
    }
}

The reason is that any statement following the for loop is unreachable, according to the rules set out in the JLS 14.21. Specifically

  1. Any for loop with no condition expression (or a condition expression that is a compile-time constant expression with value true) cannot "complete normally".

  2. Any statement in a block that is preceded by a statement which cannot complete normally is unreachable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜