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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With