Monday 28 March 2016

java - Why should I use Runnable instead of Thread?




I just learn the theory about thread. And there is Thread and Runnable.



class A extends Thread{
public void run(){
while(true) {
System.out.println("Hi");
}
}

}





class B implements Runnable{
public void run(){
System.out.println("Hi");
}
}



Thread is good with rich API, so why would I use Runnable instead of Thread?



Thanks.


Answer



1. Java doesn't support multiple inheritance, which means you can only extend one Java class, so once you extended Thread class you lost your chance and cannot extend(inherit) another class in java.



2. In OOP extending a class generally means adding new functionality, modifying or improve behaviors. If you are not making any modification on Thread, then use Runnable interface instead.




3. Implementing Runnable makes your class more flexible(you can implement more than one interface).


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...