abhishek bhalwal
abhishek bhalwal

Reputation: 1

Does Callable interface is also used to create thread like Runnable??

Does Callable interface is also used to create thread like Runnable??

As I have used it with executer framework so it work like same as runnable. I have seen only two traditional ways to create a Thread so far till now. Please Help

Upvotes: 0

Views: 185

Answers (2)

Nathan Hughes
Nathan Hughes

Reputation: 96395

Runnable and Callable are similar, they are both ways to specify a task which can be performed by an Executor. Callable exists for tasks that need to return a result.

Runnable and Callable are not used to "create a thread". Defining objects using these interfaces lets you keep separate the specification of what task you need performed from the specification of what infrastructure should perform the task. When you create a Runnable or Callable and pass it to an Executor, the executor can do things like hand it off to an existing thread drawn from a pool (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html) or execute it in the current thread (SingleTheadExecutor). There isn't a requirement that a Runnable or Callable needs to create its own thread.

Upvotes: 1

John C
John C

Reputation: 501

You can execute a Callable<T> like a Runnable by wrapping it in a FutureTask<T> (which implements Runnable). You can retrieve the returned value by calling the <T> get() function of the FutureTask<T> you wrapped the callable with.

Upvotes: 0

Related Questions