Callable interface
Runnable interface
public interface Runnable - this interface is implemented by those classes whose instances are supposed to be executed in a different thread. This interface has only one method 'run', which takes no arguments and obviously all the classes implementing this interface need to define this method.
This interface is implemented by the Thread class as well and it's a common protocol for all the objects who wish to execute in a different thread. It's one of the ways of creating threads in Java. The other way to create a thread is by subclassing the Thread class. A class implementing Runnable interface can simply pass itself to create a Thread instance and can run thereafter. This eliminates the need of subclassing the Thread class for the purpose of executing the code in a separate thread.
As long as we don't wish to override other methods of the Thread class, it may be a better idea to implement the Runnable interface to enable multithreading capabilities to a class than enabling the same by extending the Thread class.
Callable vs Runnable
Though both the interfaces are implemented by the classes who wish to execute in a different thread of execution, but there are few differences between the two interface which are:-
- A Callable<V> instance returns a result of type V, whereas a Runnable instance doesn't
- A Callable<V> instance may throw checked exceptions, whereas a Runnable instance can't
The designers of Java felt a need of extending the capabilities of the Runnable interface, but they didn't want to affect the uses of the Runnable interface and probably that was the reason why they went for having a separate interface named Callable in Java 1.5 than changing the already existing Runnable interface which has been a part of Java since Java 1.0.
2 comments:
Thanks for the article; very good. Though, you need to "escape" the less-than and greater-than symbols used for Java generics in your examples - otherwise the generics are being parsed as markup by the browser and thus not displayed on the page.
Point taken. Many a times I forget escaping the '<' and '>' symbols in my articles. Once noticed, I come back to them and correct. I'll try to scan as many relevant articles as I can (which might take some time) to avoid any sort of un-readability to our viewers.
Thank you for picking this for me. I could correct it at least in this article :-) Keep visiting/posting!
Post a Comment