简体   繁体   中英

Future causing an infinite loop

I have Java code that looks like this...

package java.uyil.concurrent;
...


Future<> future= ...;
try {
    while(!future.isDone()) {
    }
}catch(Exception e) {
}

Basically the code is supposed to run that while loop until the future task is done. For some reason this code fails om one user's PC and the loop seems to go on forever. On other PCs it runs okay.

Am I missing something and does someone know threading and Future tasks enough to help?

So you want to block the flow until you get the result from the future. You do not need to use while loop, rather directly use future.get() which will block until you get the result.

If you cancel a Future before it starts, it will never get to isDone() == true

From the Javadoc for Future.isDone()

@return {@code true} if this task completed

If you don't want to use Future.get() you could do

while(!future.isDone() && !future.isCancelled()) {
    Thread.yield();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM