Callable objects is like a Runnable but the Callable object returns ability to monitor, cancel and obtain a result.
Future: A Future represents the result of an asynchronous computation. Its get() waits for the submitted task to complete and returns the result.
ExecutorService: submit method en-queues the submitted Callable and returns a Future to track its completion and obtain the result.
FutureTask-
Lets you run a Callable impl to directly run on a thread, instead of submitting to a ExecutorService.
Future: A Future represents the result of an asynchronous computation. Its get() waits for the submitted task to complete and returns the result.
ExecutorService: submit method en-queues the submitted Callable and returns a Future to track its completion and obtain the result.
public class CallableDemo { public static void main(String...strings ){ try { System.out.println(Thread.currentThread().getName()); ExecutorService executor=new ScheduledThreadPoolExecutor(5); Callable<Date> callable=new Callable<Date>(){ @Override public Date call() throws Exception { System.out.println(Thread.currentThread().getName()); return new Date(); } }; Future<Date> fDate=executor.submit(callable); System.out.println(fDate.get()); } catch (Exception e) {} } }
FutureTask
FutureTasktask=new FutureTask (new CallableImpl()); Thread t1=new Thread(task); t1.start(); while(!task.isDone()); task.get(); //get the result
No comments:
Post a Comment