Callable
interface has one method call in it, it is just like run method of
Runnable interface. But the main difference is, run method won't
return any value where as call method returns a value.
In
Some situation, it is necessary to return a value from a task and
throw some exception in abnormal situations. But the run method in
Runnable interface won't return any value and can't throw any
exception. Java solve that problem by providing call method in
Callable interface, call method returns any object and can throw an
exception.
V
call() throws Exception
Computes
a result, or throws an exception if unable to do so. Returns the
computed result.
CallableTask.java
import java.util.concurrent.*; import java.util.*; public class CallableTask implements Callable{ String name; CallableTask(String name){ this.name = name; } public String call(){ try{ Thread.sleep(1000); } catch(Exception e){ } return (new Date() + " :: " + name); } }
SimpleThreadPool.java
import java.util.concurrent.*; import java.util.*; class SimpleThreadPool{ public static void main(String args[])throws Exception{ List<Future<String>> l1 = new ArrayList<Future<String>> (); ExecutorService exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); CallableTask tasks[] =new CallableTask[10]; for(int i=0; i<5; i++){ tasks[i] = new CallableTask("task" + i); Future<String> future = exec.submit(tasks[i]); System.out.println("Submit the task " + i); l1.add(future); } exec.shutdown(); exec.awaitTermination(10, TimeUnit.SECONDS); for(Future f1 : l1){ System.out.println(f1.get()); } System.out.println("Execution Completed"); } }
Output
Submit the task 0 Submit the task 1 Submit the task 2 Submit the task 3 Submit the task 4 Sat Mar 08 10:40:17 IST 2014 :: task0 Sat Mar 08 10:40:17 IST 2014 :: task1 Sat Mar 08 10:40:17 IST 2014 :: task2 Sat Mar 08 10:40:18 IST 2014 :: task3 Sat Mar 08 10:40:18 IST 2014 :: task4 Execution Completed
ExecutorService
exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new
LinkedBlockingQueue<Runnable>())
Statement
creates a thread pool of 3 threads.
exec.submit(tasks[i])
Submit
the tasks to the thread pool. When the task is submitted, ThreadPool
assigns a thread to execute the call method of the Callable Object.
exec.awaitTermination(10,
TimeUnit.SECONDS)
Block the execution of the current
thread for atmost 10 seconds, untill all the tasks finsishes. If all
the tasks finishes before 10 seconds, it unblocks and proceed next
statements executions.
No comments:
Post a Comment