面试题答案
一键面试- 判断任务是否已完成:
isDone()
方法:该方法用于判断任务是否已经完成,无论任务是正常完成、因异常完成还是被取消,只要任务结束,该方法都会返回true
。
import java.util.concurrent.CompletableFuture; public class CompletableFutureStatusExample { public static void main(String[] args) { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return "Task completed"; }); // 检查任务是否完成 boolean isCompleted = future.isDone(); System.out.println("任务是否完成: " + isCompleted); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } isCompleted = future.isDone(); System.out.println("任务是否完成: " + isCompleted); } }
- 判断任务是否已取消:
isCancelled()
方法:该方法用于判断任务是否被取消。只有在任务正常完成前调用了cancel(true)
方法,并且任务能够响应中断时,该方法才会返回true
。
import java.util.concurrent.CompletableFuture; public class CompletableFutureCancelExample { public static void main(String[] args) { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { while (true) { if (Thread.currentThread().isInterrupted()) { System.out.println("任务被中断"); return "任务被取消"; } try { Thread.sleep(1000); System.out.println("任务执行中..."); } catch (InterruptedException e) { Thread.currentThread().interrupt(); System.out.println("任务被中断"); return "任务被取消"; } } }); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } boolean isCancelled = future.cancel(true); System.out.println("任务是否取消: " + isCancelled); isCancelled = future.isCancelled(); System.out.println("任务是否取消: " + isCancelled); } }