"implements Runnable" vs. "extends Thread"

There are two ways to create thread in java
  

public class A implements Runnable{

 public void run() {
  
 }

}

public class B extends Thread{

  public void run() {
   
  }
}

In general, most of the people recommend using something like Runnable rather than Thread because it allows you to keep your work only loosely coupled with your choice of concurrency.
For example, if you use a Runnable and decide later on that this doesn't in fact require it's own Thread, you can just call threadA.run().

And implements Runnable is the preferred way to do it, You're not really specialising the thread's behaviour, you're just giving it something to run.
In practical terms, it means you can implement Runnable and derive from anything else as well.

one more reason to implement Runnable instead of extend Thread: Java only supports single inheritance, so you can only extend one class.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...