Kotlin-Demo/bunny/async/CallableWithFutureTest.java

35 lines
1.2 KiB
Java
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package bunny.async;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableWithFutureTest {
public static void main(String[] args) throws Exception {
try (ExecutorService executorService = Executors.newSingleThreadExecutor()) {
Callable<Integer> task = () -> {
Thread.sleep(1000);
return 42;
};
Future<Integer> future = executorService.submit(task);
// 是否完成
boolean done = future.isDone();
System.out.println("是否完成:" + done);
// 等待任务执行完成并获取结果,方法会阻塞,直到等到结果或者结果超时
Integer result = future.get();
// 取消操作
boolean cancel = future.cancel(true);
System.out.println("是否取消:" + cancel);
// 是否在任务完成前取消如果是返回true
boolean cancelled = future.isCancelled();
System.out.println("是否在任务完成前取消:" + cancelled);
System.out.println("任务结果: " + result);
}
}
}