Callable Threads vs. Runnable Threads vs. Extend Thread
I recently read about creating threads in java using implementing Runnable
or Extending thread
and last Implementing Callable
. Runnable Versus Callable thread on stackoverflow describes the difference quoting both are designed for classes whose instances are potentially executed by another thread
. What does it mean? Is he creating a new topic? If so, why do we need to pass a class that implements the constructor Runnable
in Thread
?
Also, I've seen a method for creating threads implementing Runnable
or Extending thread
. In the first method (in the tutorials I found), we need to call a class Thread
that requires an instance to Runnable
start a thread. But I couldn't find a similar one for Callable
as there is no Thread constructor that accepts Callable
. Executor framework
or Future Task
used to start these threads. Then why do we say both paths are the same (except Callable, something extracts and may throw an exception).
The last one writes
Thread t = new Thread();
Thread t1 = new Thread(new RunnableInstance());
Do they create new threads in the system? Is there any other way to use it Runnable
to create new threads without passing it as a constructor to the class Thread
?
This should not be a duplicate question.
source to share
What does it mean? Is he creating a new topic?
Both Callable and Runnable are just interfaces, they don't create threads themselves. Instead, they provide APIs and abstractions for developers. When you want to execute some code in a separate thread, you usually implement Runnable and then you can decide how to execute it. He's not connected to anything yet. You actually have many options:
- Run it on a new topic
- Execute it with some ExecutorService
- Or just call it directly
If so, why do we need to pass a class that implements the Runnable to Thread construct?
Not. Since Runnable doesn't create a thread behind (well, it just can't, since it's just an interface!), We have to explicitly execute this Runnable.
Do they create new threads in the system?
Yes.
Is there any other way to use Runnable to create new threads without passing it as a constructor to the Thread class?
Yes. I have already mentioned the Executive Office. You can profit from a thread pool or completion service, take a look at the API and examples .
source to share
Callable
and Runnable
provide interfaces for other classes to execute on threads. They do not contain any functionality. The most common way to do this is through ExecutorService
. Take a look at the classes available in java.until.concurrent
. There are many options out there. The extension Thread
is not actually called, unless you really intend to add new low-level streaming functionality.
source to share