Reputation: 1178
I was recently reading about creation of Threads in java by implementing Runnable
or Extending thread
and last Implementing Callable
. Runnable Versus Callable thread at stackoverflow describes the difference quoting both are designed for classes whose instances are potentially executed by another thread
. What does it mean? Does it creates new Thread? If yes, why we need to pass a class that implements Runnable
to Thread
constructor?
Also, i saw the method of creating threads by implementing Runnable
or Extending thread
. In the first method, (in the tutorials what i found), we need to call Thread
class which requires the Runnable
instance to start the thread. But, i could not found the similar thing for Callable
as there is no Thread constructor which accepts Callable
. Executor framework
or Future Task
is used for the purpose of running those threads. Then why we say both ways are same (except Callable retruns something and can throw Exception).
Last, is writing
Thread t = new Thread();
Thread t1 = new Thread(new RunnableInstance());
Do these create new Threads in system? Is there any other way of using Runnable
to create new threads without passing it as a constructor to Thread
class?
It should not be a duplicate question.
Upvotes: 3
Views: 2624
Reputation: 9716
What does it mean? Does it creates new Thread?
Both Callable and Runnable are just interfaces, they don't create any threads by themself. Instead they provide API and abstractions for developers. When you want to execute some code in separate thread you typically implement Runnable and then you can decide how to execute this. It is not bound to any thread yet. You have many options actually:
If yes, why we need to pass a class that implements Runnable to Thread constructor?
No. Since Runnable does not create thread behind (well, it simply can't since it's just an interface!), we need to execute this Runnable explicitly.
Do these create new Threads in system?
Yes.
Is there any other way of using Runnable to create new threads without passing it as a constructor to Thread class?
Yes. I mentioned already ExecutorService. You can profit from thread pool or completion service, take a look at the API and examples.
Upvotes: 3
Reputation: 3836
Callable
and Runnable
provides interfaces for other classes to execute them in threads. They contain no functionality of their own. The most common way to do this is via an ExecutorService
. Have a look at the classes available in java.until.concurrent
. There are many options there. Extending Thread
is not really called for unless you really intend to add new low-level threading functionality.
Upvotes: 1
Reputation: 2006
Callable
It will return the result of the execute.
Runnable
It wont return. But it will run separately like callable.
Extends Thread
Its also a runnable. But if you extend thread , you cant extend any class since java wont support multiple inheritance.
Upvotes: 1