Giriş
Şu satırı dahil ederiz
import java.util.concurrent.CancellationException;
Future.cancel() edildikten sonra Future.get() metodunu çağırmak CancellationException fırlatılmasına sebep olur
Örnek - Future
Şöyle yaparız.
ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit(() -> { // Simulating a task that takes some time to complete Thread.sleep(5000); return "Task result"; }); // Cancel the task before it completes boolean canceled = future.cancel(true); try { String result = future.get(); System.out.println("Task result: " + result); } catch (CancellationException e) { System.out.println("Task was canceled."); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } executor.shutdown();
Hiç yorum yok:
Yorum Gönder